抽象工厂模式用于封装一组具有共同目标的单个工厂。它能够将一组对象的实现细节从一般用法中分离出来。
应用场景:一个系统必须独立于它所创建的对象的生成方式,或它需要与多种对象类型一起工作。
接着上期我们已经实现了简单工厂模式实例如:
// 定义一个 white(白酒) 构造函数
function White(options) {
this.brand = options.brand || '茅台', // 品牌
this.proof = options.proof || '45' // proof 酒精度
}
// 定义一个 red(红酒) 构造函数
function Red(options) {
this.brand = options.brand || '拉菲', // 品牌
this.proof = options.proof || '12' // proof 酒精度
}
// 定义一个wine 工厂的大体代码
function Wine() {}
// 定义该工厂的默认类型 为 白酒
Wine.prototype.wineClass = White;
// 创建酒的实例的工厂方法
Wine.prototype.createWine = function(options) {
if (options.type === 'white' ) {
this.wineClass = White;
} else {
this.wineClass = Red;
}
return new this.wineClass(options);
}
// 创建生成白酒的工厂实例
var whiteWine = new Wine();
var white = whiteWine.createWine({
type: 'white',
brand: '五粮液',
proof: '53'
})
console.log(white) // White {brand: "五粮液", proof: "53"}
// 创建生成红酒的工厂实例
var red = whiteWine.createWine({
type: 'red',
brand: '白兰地',
proof: '22'
})
console.log(red) // Red {brand: "白兰地", proof: "22"}
如果我们需要另一种类型的酒,如黄酒,我们如果用简单的工厂模式的话,我们需要修改Wine 工厂代码,我们接下来利用抽象工厂模式进行改造,方便我们后期在增加其他类型时,无须修改wine工厂,具体如下:
var AbstractWine = (function(){
var types = {}
return {
getWine: function(type, options) {
var Wine = types[type]
if (Wine {
return new Wine(options)
} else {
return null
}
}
// type 注册酒类型 如:白酒、红酒 Wine 白酒、红酒的构造函数
registerWine: function(type, Wine) {
if (type && Wine) {
types[type] = Wine;
}
return AbstractWine
}
}
})()
// 用法
// 我们新注册一个黄酒
AbstractWine.registerWine('yellow', Yellow);
var yellowWine = AbstractWine.getWine('yellow', {
type: 'yellow',
brand: '黄酒',
proof: '43'
})
如有侵权,请发邮箱至wk_daxiangmubu@163.com 或留言,本人会在第一时间与您联系,谢谢!!
