Skip to content

Instantly share code, notes, and snippets.

@wolivera
Last active July 27, 2022 10:25
Show Gist options
  • Save wolivera/c699a2562c31f5dcfcb5668f40f5a413 to your computer and use it in GitHub Desktop.
Save wolivera/c699a2562c31f5dcfcb5668f40f5a413 to your computer and use it in GitHub Desktop.
GoF Factory Pattern
// 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
@JonCatmull
Copy link

Class Truck's getPrice method I think has a mistake, the url parameter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment