工厂模式介绍
工厂模式是一个创建型的模式,主要就是创建对象。其中工厂模式又分为简单工厂模式和抽象工厂模式。简单工厂模式是通过工厂方法确定创建 对应类型的对象。抽象工厂模式是通过子类来实现,成员实例化推迟到子类中进行。工厂模式都拥有相同的接口。
工厂模式一般用于:创建相似对象时的重复操作,不知道对象类型提供创建对象的接口。下面我们模式飞机大战游戏中的飞机类型进行工厂模式示例。
工厂模式示例
工厂模式示例如下:
/*构建飞机工厂(飞机大战游戏中的飞机)*/
var AirplaneFactory = function(){}; AirplaneFactory.prototype = {
createAirplane:function(model){
var plan;
switch(model){
case 'General':
plan = new GeneralPlan();
break;
case 'Boss':
plan = new BossPlan();
break;
}
return plan;
}
}
/*一般炮灰飞机*/
var GeneralPlan = function(){};
GeneralPlan.prototype = {
name:'general paln',
type:'general',
getName:function(){
return this.name;
},
getType:function(){
return this.type;
}
}
/*BOSS 飞机*/
var BossPlan = function(){};
BossPlan.prototype = {
name:'boss plan',
type:'boss',
getName:function(){
return this.name;
},
getType:function(){
return this.type;
}
}
/*通过工厂生成 相应的飞机*/
var myPlan = new AirplaneFactory().createAirplane('Boss');
console.log(myPlan.getName());
var myPlan2 = new AirplaneFactory().createAirplane('General');
console.log(myPlan2.getName());
工厂模式总结
在JavaScript中使用工厂模式的主要弱化了对象间的耦合,简化更换或者选择类,防止代码的重复工作。
来源:oschina
链接:https://my.oschina.net/u/1586502/blog/222220