简略工厂模式

定义:简略工厂模式中,能够依据参数的不同返回不同类的实例。简略工厂模式专门定义一个类来负责创立其余类的实例,被创立的实例通常都具备独特的父类。
对于简略工厂我看了很多文档,仍旧没有打消我的纳闷(构造函数是否是简略工厂???)
因而,我在上面的文档中会把构造函数也放入简略工厂中(如果我的了解有误,还望海涵)

// 因为在我的认知中, 构造函数和上面的办法惟一的区别就是是否能找到创立这个对象的办法// 构造函数function SingleFactory(name) {  this.name = name}// 简略工厂// 传入参数,创立相应实例function singleFactory(name) {  return new Object({ name })}const sfp = new SingleFactory('小猫')const sf = singleFactory('小狗')console.log(sfp) //SingleFactory {name: '小猫'}console.log(sf) // {name: '小狗'}

工厂办法模式

定义:工厂办法模式中,工厂父类负责定义创立产品对象的公共接口,而工厂子类则负责生成具体的产品对象,这样做的目标是将产品类的实例化操作提早到工厂子类中实现,即通过工厂子类来确定到底应该实例化哪一个具体产品类。
在工厂办法中,咱们只须要保护工厂办法的属性,就能够实现不同的类

function Animals(name) {  return new this[name]()}Animals.prototype = {  Cat: function () {    this.animals = ['橘猫', '狸花猫']  },  Dog: function () {    this.animals = ['中华田园犬', '厉害大藏獒']  },}var dog = new Animals('Dog')var cat = new Animals('Cat')console.log(dog) // Dog {animals: Array(2)}console.log(cat) // Cat {animals: Array(2)}

当然依照我的了解,咱们不仅须要反对 new 的构造函数的写法,仍然要反对函数调用的模式,把下面的代码调整一下。

function Animals(name) {  if (this instanceof Animals) {    return new this[name]()  } else {    return new Animals(name)  }}Animals.prototype = {  Cat: function () {    this.animals = ['橘猫', '狸花猫']  },  Dog: function () {    this.animals = ['中华田园犬', '厉害大藏獒']  },}var dog = new Animals('Dog')var cat = Animals('Cat')console.log(dog) // Dog {animals: Array(2)}console.log(cat) // Cat {animals: Array(2)}

这样,咱们就反对 new 去结构一个对象或者间接调用函数去结构一个对象

形象工厂模式

定义:形象工厂模式是指当有多个形象角色时,应用的一种工厂模式。形象工厂模式能够向客户端提供一个接口,使客户端在不用指定产品的具体的状况下,创立多个产品族中的产品对象

function Animals(subType, superType) {  if (typeof Animals[superType] === 'function') {    // 这里其实有个知识点, 构造函数的几种继承形式,这里应用的是最正当的组合寄生继承,当然本文不会去详解继承的形式    // 用来继承父类的容器    var F = function () {}    // F 函数的原型指向 Animals 子类的实例    F.prototype = new Animals[superType]()    // subType 子类的结构器指向本身    subType.constructor = subType    // subType 子类的原型指向父类    subType.prototype = new F()  } else {    throw new Error('Animals 没有该抽象类')  }}Animals.Cat = function () {  this.type = '小猫'}Animals.Cat.prototype = {  execVoice: function () {    return new Error('该办法须要被重写')  },}Animals.Dog = function () {  this.type = '小狗'}Animals.Dog.prototype = {  execVoice: function () {    return new Error('该办法须要被重写')  },}function Dog(name, voice) {  this.name = name  this.voice = voice}function Cat(name, voice) {  this.name = name  this.voice = voice}Animals(Dog, 'Dog')Animals(Cat, 'Cat')Dog.prototype.execVoice = function () {  return this.voice}Cat.prototype.execVoice = function () {  return this.voice}var dog = new Dog('旺财', '汪汪汪')var cat = new Cat('思乡', '喵喵喵')console.log(dog, dog.execVoice()) // Dog '汪汪汪'console.log(cat, cat.execVoice()) // Cat '喵喵喵'