在JS中创建对象会习惯的使用 new 关键字和类构造函数(当然主要还是对象字面量),问题在于这样会导致两个类之间产生依赖性。
工厂模式就是一种有助于消除两个类依赖性的模式。
- 简单工厂模式:使用一个类(通常为单体)来生成实例。
- 复杂工厂模式:使用子类来决定一个成员变量应该是哪个具体的类的实例。
## 简单工厂模式
```js
let ComputerFactory = function(){}
function MacComputer() {}
function WinComputer() {}
ComputerFactory.prototype = {
makeProduct: function (model) {
let product
switch (model) {
case "mac":
product = new MacComputer()
break
case "win":
product = new WinComputer()
break
default:
break
}
return product;
}
}
let factory = new ComputerFactory()
let mac = factory.makeProduct('mac')
let win = factory.makeProduct('win')
```
## ES6
```js
class Computer {
constructor () {
this.product = 'Computer'
}
}
class MacComputer extends Computer {
constructor () {
super()
this.name = 'MacComputer'
}
}
class WinComputer extends Computer {
constructor () {
super()
this.name = 'WinComputer'
}
}
function ComputerFactory (param) {
let product = null
switch (param) {
case 'mac':
product = new MacComputer()
break
case 'win':
product = new WinComputer()
break
default:
break
}
return product
}
let mac = ComputerFactory('mac')
let win = ComputerFactory('win')
```