设计模式——工厂模式
工厂方法模式:
定义:工厂模式定义创建对象的接口,但是让子类去真正的实例化。也就是工厂方法将类的实例化延迟到了子类;
缺点:该方法比简单工厂模式复杂,引入了抽抽象层(空的),还有子工厂;
优点: 但是相比于简单工厂模式,代码的维护性和扩展性提高了,新增产品时,只需要在抽象成原型上增加该子工厂类即可,不需要修改抽象工厂类和其他子工厂;更符合面向对象的开闭原则;
下面一个demo:了解工厂方法模式的便捷之处;
//引入一个抽象层:PlaneFactory
function PlaneFactory () {
}
//公共接口:所有的子类实例化的对象都可以使用该接口;(新增接口时,只需在原型上增加方法即可);
PlaneFactory.prototype.touch = function () {
console.log('die');
}
//子类工厂:都定义在原型上;(新增产品时只需在原型上增加方法(子工厂)即可)
PlaneFactory.prototype.SmallPlane = function () {
this.name = 'SmallPlane';
this.width = 100;
this.height = 100;
this.blood = 100;
}
PlaneFactory.prototype.SmartPlane = function () {
this.name = 'SmartPlane';
this.width = 50;
this.height = 50;
this.blood = 100;
this.track = function () {
console.log('track');
}
}
PlaneFactory.prototype.AttackPlane = function () {
this.name = 'AttackPlane';
this.width = 200;
this.height = 200;
this.blood = 100;
this.attack = function () {
console.log('attack');
}
}
PlaneFactory.creat = function (type) {
//根据type判断PlaneFactory的原型上有没有该type的子工厂;
if (PlaneFactory.prototype[type] == undefined) {
throw 'no this constructor';
}
//有的化再看下该子工厂是否和PlaneFactory具备继承关系;
if (PlaneFactory.prototype[type].prototype.__proto__ !== PlaneFactory.prototype) {
PlaneFactory.prototype[type].prototype = new PlaneFactory();
}
var oNewPlane = new PlaneFactory.prototype[type];
return oNewPlane;
}
//实现工厂方法创建对象:
var oP1 = PlaneFactory.creat("SmallPlane");
var oP2 = PlaneFactory.creat("SmallPlane");
var oSP = PlaneFactory.creat("SmartPlane");
var oAP = PlaneFactory.creat("AttackPlane");
当然具体场景具体分析,要根据实际开取舍发复杂性和扩展性;
来源:CSDN
作者:cnailili
链接:https://blog.csdn.net/cnailili/article/details/104460200