JavaScript Factory Pattern


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. function VehicleFactory() {}
  2.  
  3. VehicleFactory.prototype.vehicleClass = Car;
  4. VehicleFactory.prototype.getVehicle = function (options) {
  5. return new this.vehicleClass(options);
  6. };
  7.  
  8. var carFactory = new VehicleFactory();
  9. var car = carFactory.getVehicle({ color: "yellow", turbo: true });
  10.  
  11. console.log(car instanceof Car); // => true
  12.  
  13. // approach #1: Modify a VehicleFactory instance to use the Truck class
  14. carFactory.vehicleClass = Truck;
  15. var mover = carFactory.getVehicle({ enclosedCargo: true, length: 26 });
  16. counsole.log(mover instanceof Truck); // => true
  17.  
  18. // approach #2: Subclass VehicleFactory to create a factory class that
  19. // builds Trucks
  20. function TruckFactory () {}
  21.  
  22. TruckFactory.prototype = new VehicleFactory();
  23. TruckFactory.prototype.vehicleClass = Truck;
  24.  
  25. var truckFactory = new TruckFactory();
  26. var bigfoot = truckFactory.getVehicle({ monster: true, cylinders: 12 });
  27.  
  28. console.log(bigfoot instanceof Truck); // => true

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.