简略工厂模式,又被称为动态工厂办法。通过一个工厂对象来创立某一种产品对象的实例,次要是用来创立同一种类型的对象
简略来说就是通过一个办法决定到底要创立那个类的实例
咱们用水果来举例
那代码如何写呢?
首先,咱们须要创立一系列水果的形象产品
类实例化工厂函数
// 创立苹果类class Apple { constructor(){ this.name = 'apple' } getColor(){ return 'Red' }}// 创立香蕉类class Banana { constructor(name){ this.name = 'banana' this.count = 10 } getCount(){ return this.count-- }}
创立了很多水果类,每个水果类能够实现本人的一系列逻辑,而具体的到底要用哪个类名创立你想要的水果你是不须要关怀的,所以咱们须要一个工厂,用来生产这些水果实体,那如何生产呢?
定义一个Fruits工厂类
class Fruits { constructor(type){ switch(type){ case 'apple': return new Apple() case 'banana': return new Banana() } }}
咱们在应用的时候只须要new Fruits,传入你想实例化的内容,就可能失去相应的水果实体
const apple = new Fruits('apple')// apple.name => apple// apple.getColor() => Redconst banana = new Fruits('banana')// banana.name => banana// banana.getCount => 10
这样提供给他人的时候就不须要那么多的累,他们只有晓得Fruits和type就能失去本人想要的后果
看到这里可能就有同学会说了,下面创立各种水果类的时候,很多中央是雷同的,雷同的局部也是能够提取进去的,简略工厂模式最次要的理念就是创建对象,创立一个水果可能有很多雷同的局部,当然还有一部分不同的局部,咱们也能够创立一个公共的创立水果类的办法
于是就有了以下代码
创立新对象模式
class creatFruit{ constructor(name, color, count){ this.name = name this.color = color this.count = count } getColorName(){ return this.color + this.name }}// 你也能够const creatFruit = ({name, color, count}) => ({ name, color, count, getColorName() { return this.color + this.name }})
你会发现其实创立水果类也能够应用工厂模式,最终创立水果能够这样写
const apple = new creatFruit('apple', 'red', 10)const banana = new creatFruit('banana', 'yellow', 20)// apple.getColorName() => redapple// banana.getColorName() => yellowbanana// 或者能够这样const apple = creatFruit({name: 'apple', color: 'red', count:10})// apple.getColorName() => redapple
应用这种形式,咱们还能够将数组转换为键值对象
const createObjectFromArray = ([key, value]) => ({ [key]: value});// createObjectFromArray(['name', 'FE情报局']) => {name: 'FE情报局'}
总结
下面其实给到了大家两种应用工厂函数的形式,第一种是通过类实例化的形式进行的创立。第二种是通过扩大对象的模式,用函数返回一个新的对象的模式。
第一种的益处是,如果这些类来自同一个父类,那其中父类原型上的办法是能够共用的
然而第二种因为是通过函数返回了一个新的对象,其办法不具备共用性