02 工厂模式
工厂模式:
最典型特征:调用一个函数返回一个类的实例。这个函数可以直接调用如fn() 或者类的静态方法。 Factory.create() create就是Factory的静态方法。
class Plant{ constructor(name){ this.name=name } grow(){ console.log('grow'); } } class Apple extends Plant{ constructor(name,taste){ super(name) this.taste =taste } } const apple1=new Apple('apple1','sweet') console.log(apple1);
简单工厂模式
class Plant{ constructor(name,taste){ this.name=name; this.taste=taste; } } class Apple extends Plant{ } class Orange extends Plant{ } // 工厂模式典型特征:调用一个函数,返回一个类的实例对象。 /** 简单工厂模式 */ class Factory{ static create(type){ if(type==='apple'){ return new Apple('苹果','甜的') } if(type==='orange'){ return new Orange('橘子','酸的') } else throw Error('没有这个水果') } } // 调用一个类的静态方法,返回一个类的实例对象 const apple=Factory.create('apple') console.log(apple);
举例子
简单工厂模式违背了
工厂方法模式
核心的工厂类不在负责所有产品的创建,而是将具体的产品创建工作交给子类完成