javascript优化--10模式(设计模式)01
单体模式:保证一个特定类仅有一个实例;即第二次使用同一个类创建新对象时,应该得到与第一个所创建对象完全相同对象;
- 在JS中,可以认为每次在使用对象字面量创建对象的时候,实际上就在创建一个单体;
- 当使用new创建新对象时
- 使用静态属性中的实例:
function Universe() {
if(typeof Universe.instance === 'object') {
return Universe.instance;
}
this.start_time = 0;
this.bang = 'Big';
Universe.instance = this;
return this;
} - 采用闭包包含单个实例:
function Universe1() {
var instance = this;
this.start_time = 0;
this.bang = 'Big';
Universe1 = function() {
return instance;
}
}var Universe;
(function () {
var instance;
Universe = function Universe() {
if(instance) {
return instance;
}
instance = this;
//增加功能
this.start_time = 0;
this.bang = 'Big';
}
})();
- 使用静态属性中的实例:
工厂模式:
根据字符串指定地类型在运行时创建对象地方法
工厂模式地目的使为了创建对象
- 当创建对象时执行重复操作
- 再编译时不知道具体类型地情况下,为工厂客户提供一个创建对象的接口
function CarMaker() {};
CarMaker.prototype.drive = function() {
return "Vroom, I have " + this.doors + " doors";
};
CarMaker.factory = function(type) {
var constr = type, newcar;
//如果构造函数不存在,则抛出错误
if(typeof CarMaker[constr] != "function") {
throw {
name: "Error",
message: constr + " doesn't exist"
};
}
//构造函数是已知存在的;使原型继承父类,但仅继承一次
if(typeof CarMaker[constr].prototype.drive !== 'function') {
CarMaker[constr].prototype = new CarMaker();
}
//创建一个新的实例
newcar = new CarMaker[constr]();
//选择性地调用一些方法,然后返回
return newcar;
};
CarMaker.Compact = function() {
this.doors = 4;
};
CarMaker.Convertible = function() {
this.doors = 2;
}
CarMaker.SUV = function() {
this.doors = 24;
}
var corolla = CarMaker.factory('Compact');
var solstice = CarMaker.factory('Convertible');
var cherokee = CarMaker.factory('SUV');
corolla.drive();
solstice.drive();
cherokee.drive();
内置对象工厂:对于自然工厂的例子,可以考虑内置的Object()构造函数;它也根据输入类型而创建不同的对象;
迭代器模式:
提供一个API来遍历或操纵复杂地自定义数据结构
迭代访问一个包含某些数据集合的对象的模式;
var agg = (function() {
var index = 0, data = [1,2,3,4,5], length = data.length;
return {
next: function() {
var element;
if(!this.hasNext()) {
return null;
}
element = data[index];
index = index + 2;
return element;
},
hasNext: function() {
return index < length;
},
//重置指针到初始化位置
rewind: function() {
index = 0;
},
//返回当前元素
current: function() {
return data[index];
}
}
}());
//测试
while(agg.hasNext()) {
console.log(agg.next());
}
agg.rewind();
console.log(agg.current());
装饰者模式
可以再运行时动态添加附加功能到对象中;比较方便的特征时其预期行为可制定和可配置;
function Sale(price) {
this.price = price || 100;
}
Sale.prototype.getPrice = function() {
return this.price;
}
Sale.decorators = {};
//增加联邦税
Sale.decorators.fedtax = {
getPrice: function() {
var price = this.uber.getPrice();
price += price * 5/ 100;
return price;
}
};
//增加省级税
Sale.decorators.quebec = {
getPrice: function() {
var price = this.uber.getPrice();
price += price * 7.5 /100;
return price;
}
};
//转化为美元
Sale.decorators.money = {
getPrice: function() {
return "$" + this.uber.getPrice().toFixed(2);
}
};
//格式化为CDN
Sale.decorators.cdn = {
getPrice: function() {
return "CDN$ " + this.uber.getPrice().toFixed(2);
}
};
Sale.prototype.decorate = function(decorator) {
var F = function() {},
overrides = this.constructor.decorators[decorator],
i, newobj;
F.prototype = this;
newobj = new F();
newobj.uber = F.prototype;
for(i in overrides) {
if(overrides.hasOwnProperty(i)) {
newobj[i] = overrides[i];
}
}
return newobj;
}
var sale = new Sale(100);
sale = sale.decorate('fedtax');
sale = sale.decorate('quebec');
sale = sale.decorate('money');
sale.getPrice();
var newsale = new Sale(200);
newsale = newsale.decorate('cdn');
newsale.getPrice();
使用列表实现
function Sale(price) {
this.price = price;
this.decorators_list = [];
}
Sale.decorators = {};
Sale.decorators.fedtax = {
getPrice: function(price) {
return price + price * 5 / 100;
}
};
Sale.decorators.quebec = {
getPrice: function(price) {
return price + price * 7.5 /100;
}
};
Sale.decorators.money = {
getPrice: function(price) {
return "$" + price.toFixed(2);
}
};
Sale.prototype.decorate = function(decorator) {
this.decorators_list.push(decorator)
};
Sale.prototype.getPrice = function() {
var price = this.price, i, max = this.decorators_list.length, name;
for(i = 0; i < max; i++) {
name = this.decorators_list[i];
price = Sale.decorators[name].getPrice(price);
}
return price;
}
var sale = new Sale(100);
sale.decorate('fedtax');
sale.decorate('quebec');
sale.decorate('money');
console.log(sale.getPrice());
javascript优化--10模式(设计模式)01的更多相关文章
- javascript优化--11模式(设计模式)02
策略模式 在选择最佳策略以处理特定任务(上下文)的时候仍然保持相同的接口: //表单验证的例子 var data = { firs_name: "Super", last_name ...
- javascript优化--06模式(对象)01
命名空间: 优点:可以解决命名混乱和第三方冲突: 缺点:长嵌套导致更长的查询时间:更多的字符: 通用命名空间函数: var MYAPP = MYAPP || {}; MYAPP.namespace = ...
- javascript优化--12模式(设计模式)03
观察者模式 通过创建一个可观察的对象,当发生一个感兴趣的事件时将该事件通告给所有观察者,从而形成松散的耦合 订阅杂志 //发布者对象 var publisher = { subscribers: { ...
- javascript优化--08模式(代码复用)01
优先使用对象组合,而不是类继承: 类式继承:通过构造函数Child()来获取来自于另一个构造函数Parent()的属性: 默认模式:子类的原型指向父类的一个实例 function inherit(C, ...
- javascript优化--13模式1(DOM和浏览器模式)
注意分离: 通过将CSS关闭来测试页面是否仍然可用,内容是否依然可读: 将JavaScript关闭来测试页面仍然可以执行正常功能:所有连接是否正常工作:所有的表单是否可以正常工作: 不使用内联处理器( ...
- javascript优化--14模式2(DOM和浏览器模式)
远程脚本 XMLHttpRequest JSONP 和XHR不同,它不受同域的限制: JSONP请求的可以是任意的文档: 请求的URL通常格式为http://example.js?calback=Ca ...
- javascript优化--05模式(函数)
回调函数模式: 基本例子: var findNodes = function (callback) { ...................... if (typeof callback !== ' ...
- javascript优化--09模式(代码复用)02
原型继承 ://现代无类继承模式 基本代码: var parent = { name : "Papa" } var child = object(parent); function ...
- javascript优化--07模式(对象)02
沙箱模式: 解决空间命名模式的几个缺点: 命名空间模式中无法同时使用一个应用程序或库的两个版本运行在同一个页面中,因为两者需要相同的全局符号: 以点分割,需要输入更长的字符,解析时间也更长: 全局构造 ...
随机推荐
- ExtJS学习之路第三步:理解引擎之下,ExtJS4中的类
写写就发现,有些代码不查查源头,不明白是怎么回事?搜到这篇文章觉得还是收益匪浅,更容易读懂代码. Classes in Ext JS 4: Under the hood Countdown to Ex ...
- Mate7微信指纹支付来了 比Touch ID整合微信早一点
之前我们聊过微信将推指纹支付 "指付通"会与Touch ID整合吗这个话题,现在有国内厂商率先支持微信指纹支付,体验一下美国用户使用Apple Pay搭配Touch ID来实现便捷 ...
- js矩阵菜单或3D立体预览图片效果
js矩阵菜单或3D立体预览图片效果 下载地址: http://files.cnblogs.com/elves/js%E7%9F%A9%E9%98%B5%E8%8F%9C%E5%8D%95%E6%88% ...
- FineUI第三天----WebConfig的配置
这张我们讲讲整个站点Web.config配置文件的配置 Theme: 控件主题,目前支持三种主题风格(blue/gray/access,默认值:blue) Language: 控件语言(en/zh_C ...
- 5 个最受人喜爱的开源 Django 包
导读 Django 围绕“可重用应用”的思想建立:自包含的包提供了可重复使用的特性.你可以将这些可重用应用组装起来,在加上适用于你的网站的特定代码,来搭建你自己的网站.Django 具有一个丰富多样的 ...
- 【NGUI】grid下面的item的重复利用
http://blog.csdn.net/u012091672/article/details/21159075解决的问题 使用grid放置item的时候,每次数据可能都不一样,但是每次都删除grid ...
- SQL常见笔试面试题
sql理论题 1.触发器的作用? 答:触发器是一中特殊的存储过程,主要是通过事件来触发而被执行的.它可以强化约束,来维护数据的完整性和一致性,可以跟踪数据库内的操作从而不允许未经许可的更新和变化.可以 ...
- python代码中使用settings
在具体的Django应用中,通过引入 django.conf.settings 使用配置,例: from django.conf import settings settings.configure( ...
- intellij idea 如何更改编辑器文本字体和大小
换上了intellij idea之后,第一件事就是想要改变下文字字体,因为在我这个27寸的2k分辨率的屏幕上,文字显然太小了. intellij idea字体设值分成两部分,一部分是UI部分字体字号设 ...
- 【系统】CentOS、Ubuntu、Debian三个linux比较异同
CentOS.Ubuntu.Debian三个linux比较异同 2014-07-31 12:58 53428人阅读 评论(6) ...