模式类型:工厂模式
模式说明:常用模式之一,用来动态创建对象
适用范围:在运行期间需要在一系列可互换的子类中进行选择的类
注意事项:接口的实现,从而使不同子类可以被同等的对待,恰当的使用工厂模式,但不要拘泥与形式,理解本质。
关键点:以 函数/类/子类 构建的选择器
本质:函数作为选择器的使用
一般使用形式:
作为独立的选择器存在:
复制代码 代码如下:
function factorymode(index){
switch(index){
case index1 :
return new class1();break;
case index2:
return new class2();break;
case index3:
return new class3();break;
default:return new classcomm();break;
}
}
或作为类的一个方法存在:
复制代码 代码如下:
var mainclass=function(){};//主类构造器
mainclass.prototype={
factorymode:function(){}//子类选择器
}
又或隐式选择,即不以使用者的主观选择而选择:
复制代码 代码如下:
var xmlrequest=function(){
if(this.isoffonline()){
xhr= new offlinehandler();
}//如果此时网络不可用,创建可缓存ajax对象
else if(this.ishightlatency()){
xhr= new queuedhandler();
}//如果网络延迟较大,创建队列形式ajax对象
else {
xhr=new simplehandler();
}//如果网络正常,创建简单ajax对象
interface.ensureimplements(xhr,ajaxhandler);
//检查对象是否实现了接口,从而确保以后的工作可以顺利进行
return xhr;
}
延伸:
工厂模式的本质就是选择器的应用,选择器不仅可作为对象的选择,还可作为函数的选择,类的选择,参数的选择
函数的选择,如:
复制代码 代码如下:
var addevent=(function(){
if(!-[0,]){
return function(elem,type,handler){
elem[type+handler.tostring()]=handler;
elem.attachevent(on+type,elem[type+handler.tostring]);
}}//if ie
else {
return function(elem,type,handler){
elem.addeventlistener(type,handler,false);
}
}
})();//避免多次判断
类的选择:
复制代码 代码如下:
var suitableclass=function(){
if(match condition a) return class1;
else if(match condition b) return class2;
else return classcomm;
}
参数的选择:
复制代码 代码如下:
function country(country){
if(country==china)
this.config={};//设置基本参数1
else if(contry==america)
this.config={};//设置参数2
else if()
.......//等等
}
country.prototype={};