工厂方法模式

it2022-05-06  1

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

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

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

 

 

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

 

转载于:https://www.cnblogs.com/guangzhou11/p/10747730.html


最新回复(0)