Skip to content

Instantly share code, notes, and snippets.

@blogscot
Last active November 19, 2021 03:53
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save blogscot/590be1a7d295ab355f0038153190880b to your computer and use it in GitHub Desktop.
Save blogscot/590be1a7d295ab355f0038153190880b to your computer and use it in GitHub Desktop.
Factory Pattern examples using ES6 syntax
class Car {
constructor(doors = 4, state = "brand new", color = "silver") {
this.doors = doors
this.state = state
this.color = color
}
}
class Truck {
constructor(state = "used", wheelSize = "large", color = "blue") {
this.state = state
this.wheelSize = wheelSize
this.color = color
}
}
class VehicleFactory {
vehicleClass = Car
createVehicle = (type, props) => {
switch(type) {
case "car":
return new this.vehicleClass(props.doors, props.state, props.color)
case "truck":
return new this.vehicleClass(props.state, props.wheelSize, props.color)
}
}
}
// Let's build a vehicle factory!
const factory = new VehicleFactory()
const car = factory.createVehicle( "car", {
doors: 6,
color: "green"
})
console.log(JSON.stringify(car))
const truck = factory.createVehicle( "truck", {
state: "like new",
color: "red",
wheelSize: "small"
})
console.log(JSON.stringify(truck))
// Let's build a truck factory!
class TruckFactory extends VehicleFactory {
vehicleClass = Truck
}
const truckFactory = new TruckFactory()
const bigTruck = truckFactory.createVehicle( "truck", {
state: "omg ... so bad",
color: "pink",
wheelSize: "so BIG"
})
console.log(JSON.stringify(bigTruck))
@R-A-S
Copy link

R-A-S commented Nov 20, 2019

A small update for the right choice of class.:

class VehicleFactory {
  vehicleClass = null;

  setVehicleClass = type => {
    switch (type) {
      case 'car':
        this.transportClass = Car;
        break;
      case 'truck':
        this.transportClass = Truck;
        break;
      default:
        break;
    }
  };

  createVehicle = (type, props) => {
    this.setVehicleClass(type);
    switch (type) {
      case 'car':
        return new this.vehicleClass(props.doors, props.state, props.color);
      case 'truck':
        return new this.vehicleClass(props.state, props.wheelSize, props.color);
    }
  };
}

What do you think about this?🙂

@santiagogm1995
Copy link

Thanks for this example. It's simple and easy to understand. ;)

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