Skip to content

Instantly share code, notes, and snippets.

@stuartambient
Forked from blogscot/myPinkTruck.js
Created November 4, 2019 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartambient/3eb980786a0a643abfdd01dd818de58c to your computer and use it in GitHub Desktop.
Save stuartambient/3eb980786a0a643abfdd01dd818de58c 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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment