sashomaga

Factory Pattern

Jun 16th, 2013
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Car(options) {
  2.     this.doors = options.doors || 4;
  3.     this.color = options.color || "white";
  4.     this.state = options.state || "brand new";
  5. }
  6.  
  7. function Truck(options) {
  8.     this.wheelSize = options.wheelSize || 4;
  9.     this.color = options.color || "black";
  10.     this.state = options.state || "used";
  11. }
  12.  
  13. function VehicleFactory() { };
  14.  
  15. // default vahicle class
  16. VehicleFactory.prototype.vehicleClass = Car;
  17.  
  18. VehicleFactory.prototype.createVehicle = function (options) {
  19.     if (options.vehicleType === "car") {
  20.         this.vehicleClass = Car;
  21.     } else {
  22.         this.vehicleClass = Truck;
  23.     }
  24.  
  25.     return new this.vehicleClass(options);
  26. };
  27.  
  28. var carFactory = new VehicleFactory();
  29. var car = carFactory.createVehicle({
  30.     vehicleType: "car",
  31.     doors: 5,
  32.     color: "red"
  33. });
  34.  
  35. console.log(car instanceof Car);
  36. console.log(car);
  37.  
  38. //modify
  39. var movingTruck = carFactory.createVehicle({
  40.     vehicleType: "truck",
  41.     wheelSize: 8,
  42.     color: "blue"
  43. });
  44.  
  45. console.log( movingTruck instanceof Truck );
  46. console.log(movingTruck);
  47.  
  48. // new factory for trucks
  49. function TruckFactory () {}
  50. TruckFactory.prototype = new VehicleFactory();
  51. TruckFactory.prototype.vehicleClass = Truck;
  52.  
  53. var truckFactory = new TruckFactory();
  54. var myBigTruck = truckFactory.createVehicle( {
  55.     state: "bad",
  56.     color: "pink",
  57.     wheelSize: "big" } );
  58.  
  59. console.log( myBigTruck instanceof Truck );
  60. console.log( myBigTruck );
Advertisement
Add Comment
Please, Sign In to add comment