简单工厂模式违背了开闭原则,扩张性不好

工厂方法模式 :
有需求就去创建工厂
新工厂继承工厂类
这样避免修改其他工厂

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

把操作对象改变成操作各自的工厂

 工厂方法模式 随笔

 

 

class Animal  {
    constructor(name)  {
        this.name=name;
    }
    eat() {
         console.log('吃什么呀')
    }
}
class  Dog  extends  Animal {
  constructor(name)  {
       super(name);
       this.call='汪汪'
  }
}

class  Cat  extends  Animal {
  constructor(name)  {
       super(name);
       this.call='喵喵'
  }
}

class DogFactory{
    create() {
        return new Dog('xiao');
    }
}

class CatFactory{
    create() {
        return new Cat('wei');
    }
}

 
 const settings={
    'dog': DogFactory,
    'cat': CatFactory
}
let dog=new settings['dog']().create();
console.log(dog);
let cat=new settings['cat']().create();
console.log(cat);

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄