Last active
July 27, 2022 10:25
-
-
Save wolivera/c699a2562c31f5dcfcb5668f40f5a413 to your computer and use it in GitHub Desktop.
GoF Factory Pattern
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
// Products | |
// Abstract Product Class | |
class Vehicle { | |
getPrice() { | |
return `What type of vehicle do you want to get the price for?`; | |
} | |
} | |
// Subclass A | |
class Car extends Vehicle { | |
getPrice() { | |
return `This car costs $2000`; | |
} | |
} | |
// Subclass B | |
class Truck extends Vehicle { | |
getPrice(url) { | |
return `This truck costs $5000`; | |
} | |
} | |
// Creators | |
// This is the class that would be using the Product | |
class VehicleFactory { | |
// Factory method | |
createVehicle(type) { | |
switch(type) { | |
case "car": | |
return new Car() | |
case "truck": | |
return new Truck() | |
} | |
} | |
} | |
const vehicleFactory = new VehicleFactory(); | |
const car = vehicleFactory.createVehicle('car'); | |
console.log(car.getPrice()); // This car costs $2000 | |
const truck = vehicleFactory.createVehicle('truck'); | |
console.log(truck.getPrice()); // This truck costs $5000 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Class
Truck
'sgetPrice
method I think has a mistake, theurl
parameter.