Last active
August 29, 2015 14:15
-
-
Save laispace/891acb78763749581b2d to your computer and use it in GitHub Desktop.
设计模式-工厂模式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ===== 1.pattern-factory.js===== | |
// Car factory | |
function Car (options) { | |
this.type = options.type || 'car'; | |
this.owner = options.owner || null; | |
this.price = options.price || null; | |
} | |
// Trunk factory | |
function Truck (options) { | |
this.type = options.type || 'truck'; | |
this.owner = options.owner || null; | |
this.price = options.price || null; | |
} | |
// Vehicle factory | |
function Vehicle () {} | |
// set default prototype to Car | |
Vehicle.prototype.supClass = Car; | |
// create vehicle with options | |
Vehicle.prototype.create = function (options) { | |
var type = options.type; | |
if (type === 'car') { | |
// create a car with Car factory | |
this.supClass = Car; | |
} else if (type === 'truck') { | |
// create a truck with Trunk factory | |
this.supClass = Truck; | |
} | |
// return a vehicle instance | |
var vehicle = new this.supClass(options); | |
return vehicle; | |
}; | |
// first we new a factory instance | |
var vehicleFactory = new Vehicle(); | |
// now we create a car | |
var car = vehicleFactory.create({ | |
type: 'car', | |
owner: 'xiaolai-1', | |
price: 11111 | |
}); | |
console.log(car); | |
// then we create a truck | |
var truck = vehicleFactory.create({ | |
type: 'truck', | |
owner: 'xiaolai-2', | |
price: 22222 | |
}); | |
console.log(truck); | |
// ===== 2.pattern-abstract-factory.j ===== | |
var AbstractFactory = (function () { | |
// store registed vehicles | |
var types = {}; | |
return { | |
// register a new vehicle type | |
register: function (type, Vehicle) { | |
// if types[type] exist | |
if (types[type]) { | |
// do nothing | |
} else { | |
// else register this new type | |
types[type] = Vehicle; | |
} | |
return this; | |
}, | |
// get vehicle from store and set custimal options generating an instance | |
get: function (type, custimalOptions) { | |
var Vehicle = types[type]; | |
if (Vehicle) { | |
return new Vehicle(custimalOptions); | |
} else { | |
// not exist | |
return null; | |
} | |
} | |
}; | |
})(); | |
// now we register two type of vehicles | |
AbstractFactory.register('car', Car); | |
AbstractFactory.register('truck', Truck); | |
// then we get instance with custimal options | |
var car = AbstractFactory.get('car', { | |
'owner': 'xiaolai-3', | |
'price': 33333 | |
}); | |
console.log(car); | |
var truck = AbstractFactory.get('truck', { | |
'owner': 'xiaolai-4', | |
'price': 44444 | |
}); | |
console.log(truck); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
什么时候用工厂模式比较爽?