定义:工厂模式定义创建对象的接口,但是让子类去真正的实例化。也就是工厂方法将类的实例化延迟到子类
function SmallPlane(){
this.width = 100;
this.height = 100;
this.boold = 100;
this.name = 'smallPlane';
}
function BigPlane(){
this.width = 200;
this.height = 200;
this.boold = 200;
this.name = 'bigPlane';
}
function FactoryPlane(type){
let newPlane;
switch(type){
case 'smallPlane':
newPlane = new SmallPlane();
break;
case 'bigPlane':
newPlane = new BigPlane();
break;
}
newPlane.die = function(){
console.log('die');
}
return newPlane;
}
const small = FactoryPlane('smallPlane');
const big = FactoryPlane('bigPlane');
对比其他方式(对象字面量,构造函数)创建对象
- 工厂类集中了所有对象的创建,便于对象创建的统一管理
- 对象的使用者仅仅是使用产品,实现了单一职责
- 便于扩展,如果新增了一种业务,只需要增加相关的业务对象类和工厂类中的生产业务对象的方法,不需要修改其他的地方
- 确实违反了开闭原则
工厂方法模式:不再有一个唯一的工厂类创建产品,而是将不同的产品交给对应的工厂子类去实现。每个产品由负责生产的子工厂来创造。如果添加新的产品,需要做的是添加新的子工厂和产品,而不需要修改其他的工厂代码。
function FactoryPlane(){
}
FactoryPlane.prototype.die = function(){
console.log('die');
}
FactoryPlane.create = function(type){
if(!FactoryPlane.prototype[type]){
throw '没有此类型飞机'
}
if(FactoryPlane.prototype[type].prototype.__proto__ != FactoryPlane.prototype){
FactoryPlane.prototype[type].prototype = new FactoryPlane();
}
const args = [].slice.call(arguments,1);
let newPlane = new FactoryPlane.prototype[type](...args);
return newPlane;
}
FactoryPlane.prototype.smallPlane = function(x,y){
this.x = x;
this.y = y;
this.width = 100;
this.height = 100;
this.boold = 100;
this.name = 'smallPlane';
}
FactoryPlane.prototype.bigPlane = function(x,y){
this.x = x;
this.y = y;
this.width = 200;
this.height = 200;
this.boold = 200;
this.name = 'bigPlane';
}
const small = FactoryPlane.create('smallPlane');
const big = FactoryPlane.create('bigPlane',10,20);