js工厂模式:
- 设计工厂模式的目的是为了创建对象
- 它通常在类或者类的静态方法中实现
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;
};
总结:该工厂模式是通过构造函数自身的静态方法factory,为该构造函数的其它的静态方法创建实例,创建的这些实例的原型是继承自本身的构造函数(new CarMaker())。
js迭代器模式:
在迭代器模式中,通常有一个包含数据集合的对象。
该数据可能存储在一个复杂数据结构内部,而要提供一种简单的方法能够访问数据结构中每个元素。
var agg = (function(){
var index = 1,
data = [1,2,3,4],
lenght = data.length,
direction,
symbol;
return {
nextPrev:function(opt){
direction = opt.direction || '';
if(!this.hasNext() || !direction){
return null;
}
//执行动作
index = eval(index+symbol+1);
},
hasNext:function(){
if(direction=='next'){
symbol = '+';
return index < lenght;
}
if(direction=='prev'){
symbol = '-';
return index > 1;
}
},
current:function(){
return index;
},
rewind:function(){
index = 0;
}
}
})();
agg.nextPrev({direction:'next'});
agg.nextPrev({direction:'prev'});
agg.current();
agg.rewind();