Revision: 58825
Updated Code
at August 3, 2012 18:42 by timsommer
Updated Code
function VehicleFactory() {} VehicleFactory.prototype.vehicleClass = Car; VehicleFactory.prototype.getVehicle = function (options) { return new this.vehicleClass(options); }; var carFactory = new VehicleFactory(); var car = carFactory.getVehicle({ color: "yellow", turbo: true }); console.log(car instanceof Car); // => true // approach #1: Modify a VehicleFactory instance to use the Truck class carFactory.vehicleClass = Truck; var mover = carFactory.getVehicle({ enclosedCargo: true, length: 26 }); counsole.log(mover instanceof Truck); // => true // approach #2: Subclass VehicleFactory to create a factory class that // builds Trucks function TruckFactory () {} TruckFactory.prototype = new VehicleFactory(); TruckFactory.prototype.vehicleClass = Truck; var truckFactory = new TruckFactory(); var bigfoot = truckFactory.getVehicle({ monster: true, cylinders: 12 }); console.log(bigfoot instanceof Truck); // => true
Revision: 58824
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at August 3, 2012 18:41 by timsommer
Initial Code
function VehicleFactory() {} VehicleFactory.prototype.vehicleClass = Car; VehicleFactory.prototype.getVehicle = function (options) { return new this.vehicleClass(options); }; var carFactory = new VehicleFactory(); var car = carFactory.getVehicle({ color: "yellow", turbo: true }); console.log(car instanceof Car); // => true // approach #1: Modify a VehicleFactory instance to use the Truck class carFactory.vehicleClass = Truck; var mover = carFactory.getVehicle({ enclosedCargo: true, length: 26 }); counsole.log(mover instanceof Truck); // => true // approach #2: Subclass VehicleFactory to create a factory class that // builds Trucks function TruckFactory () {} TruckFactory.prototype = new VehicleFactory(); TruckFactory.prototype.vehicleClass = Truck; var truckFactory = new TruckFactory(); var bigfoot = truckFactory.getVehicle({ monster: true, cylinders: 12 }); console.log(bigfoot instanceof Truck); // => true
Initial URL
Initial Description
The Factory Pattern suggests defining an interface for creating an object where you allow the subclasses to decide which class to instantiate. This pattern handles the problem by defining a completely separate method for the creation of objects and which sub-classes are able to override so they can specify the ‘type’ of factory product that will be created.
Initial Title
JavaScript Factory Pattern
Initial Tags
javascript
Initial Language
JavaScript