工厂模式
工厂模式定义创建对象的接口,但是让子类去真正的实例化。也就是工厂方法将类的实例化延迟到子类
工厂模式对比其它方式(构造函数)
- 工厂模式类集中了所有对象的创建,便于对象的创建的统一管理
- 对象的使用者仅仅是使用产品,实现了单一职责
- 便于扩展,如果新增了一种业务,只需增加相关的业务对象类和工厂类的生产业务对象的方法,不需要修改其他的地方
- 确实违反了开闭原则
大家都玩过飞机大战吧,飞机种类太多太多了,其实构造函数去做还不太理想,用工厂模式还是不错,但是它有一个弊端,违反了开闭原则
//小飞机
function SmallPlane(){
this.height = 100
this.width = 100
this.name = 'SmallPlane'
this.blod = 100
this.touch = function(){
this.blood -= 100
if(this.blod==0){
console.log('die')
}
}
}
//大飞机
function BigPlane(){
this.height = 200
this.width = 200
this.name = 'BigPlane'
this.bold = 200
this.touch = function(){
this.bold -= 100
if(this.bold == 0){
console.log('die')
}
}
}
//攻击飞机
function AtackPlane(){
this.height = 125;
this.width = 100
this.blod =100
this.name = 'AtackPlane'
this.touch = function () {
this.bold -= 100
if (this.bold == 0){
console.log('die')
}
}
this.attack = function(){
console.log('bong')
}
}
//工厂模式
function PlaneFactor(type){
var newPlane = null
switch(type){
case 'SmallPlane':
newPlane= new SmallPlane()
break;
case 'BigPlane':
newPlane = new BigPlane()
break;
case 'AtackPlane':
newPlane = new AtackPlane()
break;
}
newPlane.die = function (){
console.log('biu')
}
return newPlane;
}
工厂方法模式
不再有一个唯一的工厂类就创建产品,而是将不同的产品交给对应的工厂类去实现。每个产品由负责生产的子工厂来创造。如果添加新的产品,需要做的是添加新的子工厂和产品,而不需要修改其他的工厂代码。
工厂方法模式组成:
- 抽象工厂类:负责定义创建产品的公共接口。
- 产品子工厂:继承抽象工厂类,实现抽象工厂类提供的接口。
- 每一种产品有各自的产品类。
代码比简单工厂模式复杂了,引入了抽象层,还有子工厂,这会增加代码的复杂度和理解难度。但是相比简单工厂模式,代码的维护性和扩展性提高了,新增产品时,只需要增加对应的产品类和产品工厂类,不需要修改到抽象工厂类和其他工厂。更加符合面向对象的开闭原则
//工厂方法模式
function PlaneFactor() {
}
//子类工厂都可以使用的公共方法
PlaneFactor.prototype.touch = function () {
this.blod -= 50;
if (this.blod == 0) {
console.log('die')
}
}
PlaneFactor.prototype.die = function(){
console.log('bong')
}
//创建对象的接口
PlaneFactor.create = function (type) {
//是否存在改类型的子类工厂
if (PlaneFactor.prototype[type] == undefined) {
throw 'no this constructor'
}
//继承
if (PlaneFactor.prototype[type].prototype.__proto__ != PlaneFactor.prototype) {
PlaneFactor.prototype[type].prototype = new PlaneFactor()
}
var arg = [].slice.call(arguments,1)
var newPlane = new PlaneFactor.prototype[type](...arg)
return newPlane;
}
//真正定义子类工厂
PlaneFactor.prototype.SmallPlane = function (x, y) {
this.x = x;
this.y = y;
this.height = 100
this.width = 100
this.name = 'SmallPlane'
this.blod = 100
}
PlaneFactor.prototype.BigPlane = function (x,y) {
this.x = x;
this.y = y;
this.height = 200
this.width = 200
this.name = 'BigPlane'
this.blold = 200
}
PlaneFactor.prototype.AtackPlane = function (x,y) {
this.x = x;
this.y = y;
this.height = 125;
this.width = 100
this.blod = 100
this.name = 'AtackPlane'
this.attack = function () {
console.log('biu')
}
}
var a = PlaneFactor.create('AtackPlane',10,20)
var b = PlaneFactor.create('BigPlane',20,20)
var c = PlaneFactor.create('SmallPlane',40,20)