工厂模式
优点
- 创建复杂的对象变得容易
- 根据不同的环境创建不同的对象
- Practical for components that require similar instantiation or methods
- 减少组件耦合
缺点
function CarDoor( options ) {
this.color = options.color || 'red';
this.side = options.side || 'right';
this.hasPowerWindows = options.hasPowerWindows || true;
}
function CarSeat( options ) {
this.color = options.color || 'gray';
this.material = options.material || 'leather';
this.isReclinable = options.isReclinable || true;
}
function CarPartFactory() {}
CarPartFactory.prototype.createPart = function createCarPart( options ) {
var parentClass = null;
if( options.partType === 'door' ) {
parentClass = CarDoor;
} else if( options.partType === 'seat' ) {
parentClass = CarSeat;
}
if( parentClass === null ) {
return false;
}
return new parentClass( options );
}
var myPartFactory = new CarPartFactory();
var seat = myPartFactory.createPart( {
partType : 'seat',
material : 'leather',
color : 'blue',
isReclinable : false
} );
console.log( seat instanceof CarSeat );
console.log( seat );