简单工厂模式
简单工厂模式由一个工厂对象决定创建出哪一种产品类的实例
缺点:
1. 耦合
2.依赖具体的实现
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 Factory {
static create(name) {
switch(name) {
case 'dog':
return new Dog('狗');
case 'cat':
return new Cat('猫');
}
}
}
let dog = Factory.create('dog');
console.log(dog.call);
let cat = Factory.create('cat');
console.log(cat.call);
简单工厂模式只对一个工厂耦合,不然他要对每个对象耦合
越努力越幸运