码迷,mamicode.com
首页 > 其他好文 > 详细

工厂方法模式

时间:2019-04-22 00:38:16      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:改变   开闭原则   col   工厂方法   console   dog   技术   extends   extend   

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

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

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

技术图片

 

 

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);

 

工厂方法模式

标签:改变   开闭原则   col   工厂方法   console   dog   技术   extends   extend   

原文地址:https://www.cnblogs.com/guangzhou11/p/10747730.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!