在 JavaScript 中实现工厂模式

属于「创建型模式」。

在面向对象编程中,「工厂」是用来创建其他对象的对象,通常是一个返回对象的函数或方法,内部调用相似但不同的构造方法创建新对象。

实现

为构造函数定义一个静态方法:

function CarMaker() {}

CarMaker.prototype.drive = function() {
return `I have ${this.doors} doors`;
}

CarMaker.factory = function(type) {
const Maker = CarMaker[type];

if (typeof Maker !== 'function') {
throw new Error(`${type} 不存在!`);
}

if (typeof Maker.prototype.drive !== 'function') {
Maker.prototype = new CarMaker();
}

return new Maker();
}

CarMaker.Compact = function() {
this.doors = 4;
}

CarMaker.Convertible = function() {
this.doors = 2;
}

更多