javascript 设计模式之工厂(Factory)模式

工厂模式介绍

    工厂模式是一个建立型的模式,主要就是建立对象。其中工厂模式又分为简单工厂模式和抽象工厂模式。简单工厂模式是经过工厂方法肯定建立 对应类型的对象。抽象工厂模式是经过子类来实现,成员实例化推迟到子类中进行。工厂模式都拥有相同的接口。 this

    工厂模式通常用于:建立类似对象时的重复操做,不知道对象类型提供建立对象的接口。下面咱们模式飞机大战游戏中的飞机类型进行工厂模式示例。 spa

工厂模式示例

工厂模式示例以下: prototype

/*构建飞机工厂(飞机大战游戏中的飞机)*/
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中使用工厂模式的主要弱化了对象间的耦合,简化更换或者选择类,防止代码的重复工做。 code

相关文章
相关标签/搜索