Last active
November 19, 2021 03:53
-
-
Save blogscot/590be1a7d295ab355f0038153190880b to your computer and use it in GitHub Desktop.
Factory Pattern examples using ES6 syntax
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
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
Thanks for this example. It's simple and easy to understand. ;)