前端JavaScript设计模式-工厂模式实现

定义:工厂模式定义创建对象的接口,但是让子类去真正的实例化。也就是工厂方法将类的实例化延迟到子类
 function SmallPlane(){
      this.width = 100;
      this.height = 100;
      this.boold = 100;
      this.name = 'smallPlane';
    }
    function BigPlane(){
      this.width = 200;
      this.height = 200;
      this.boold = 200;
      this.name = 'bigPlane';
    }
     function FactoryPlane(type){
      let newPlane;
      switch(type){
        case 'smallPlane':
          newPlane = new SmallPlane();
          break;
        case 'bigPlane':
          newPlane = new BigPlane();
          break;
      }
      newPlane.die = function(){//添加公共方法
        console.log('die');
      }
      return newPlane;
    }

    const small = FactoryPlane('smallPlane');
    const big = FactoryPlane('bigPlane');
对比其他方式(对象字面量,构造函数)创建对象
  • 工厂类集中了所有对象的创建,便于对象创建的统一管理
  • 对象的使用者仅仅是使用产品,实现了单一职责
  • 便于扩展,如果新增了一种业务,只需要增加相关的业务对象类和工厂类中的生产业务对象的方法,不需要修改其他的地方
  • 确实违反了开闭原则
工厂方法模式:不再有一个唯一的工厂类创建产品,而是将不同的产品交给对应的工厂子类去实现。每个产品由负责生产的子工厂来创造。如果添加新的产品,需要做的是添加新的子工厂和产品,而不需要修改其他的工厂代码。
function FactoryPlane(){//抽象工厂类:负责定义创建产品的公共接口

    }
    FactoryPlane.prototype.die = function(){//添加公共方法
      console.log('die');
    }

    FactoryPlane.create = function(type){
      if(!FactoryPlane.prototype[type]){
        throw '没有此类型飞机'
      }

      if(FactoryPlane.prototype[type].prototype.__proto__ != FactoryPlane.prototype){//基础知识掌握
        FactoryPlane.prototype[type].prototype = new FactoryPlane();
      }
      const args = [].slice.call(arguments,1);
      let newPlane = new FactoryPlane.prototype[type](...args);
      return newPlane;
    }
    //产品子工厂:继承抽象工厂类,实现抽象工厂类提供的接口,每一种产品都有各自的工厂类
    FactoryPlane.prototype.smallPlane = function(x,y){
      this.x = x;
      this.y = y;
      this.width = 100;
      this.height = 100;
      this.boold = 100;
      this.name = 'smallPlane';
    }
    FactoryPlane.prototype.bigPlane = function(x,y){
      this.x = x;
      this.y = y;
      this.width = 200;
      this.height = 200;
      this.boold = 200;
      this.name = 'bigPlane'; 
    }

    const small = FactoryPlane.create('smallPlane');
    const big = FactoryPlane.create('bigPlane',10,20);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值