Skip to content

Instantly share code, notes, and snippets.

@UltiRequiem
Created January 13, 2022 20:40
Show Gist options
  • Save UltiRequiem/5bf87e24986c66e8579e8924adcc5146 to your computer and use it in GitHub Desktop.
Save UltiRequiem/5bf87e24986c66e8579e8924adcc5146 to your computer and use it in GitHub Desktop.
Builder Patron JavaScript
class VehiclesFactory {
static build(builder) {
builder.addParts();
return builder.get();
}
}
class CarBuilder {
constructor() {
this.car = new Car();
}
addParts() {
this.car.addPart("engine");
this.car.addPart("wheels");
this.car.addPart("doors");
}
get() {
return this.car;
}
}
class TruckBuilder {
constructor() {
this.truck = new Truck();
}
addParts() {
this.truck.addPart("engine");
this.truck.addPart("wheels");
this.truck.addPart("doors");
this.truck.addPart("rock_decorations");
}
get() {
return this.truck;
}
}
class Car {
constructor() {
this.parts = [];
this.name = "Car";
}
addPart(part) {
this.parts.push(part);
}
say() {
console.log(`I'm a ${this.name} with ${this.parts.join(", ")}.`);
}
}
class Truck {
constructor() {
this.parts = [];
this.name= "Truck";
}
addPart(part) {
this.parts.push(part);
}
say() {
console.log(`I'm a ${this.name} with ${this.parts.join(", ")}.`);
}
}
const carBuilder = new CarBuilder();
const truckBuilder = new TruckBuilder();
const car = VehiclesFactory.build(carBuilder);
const truck = VehiclesFactory.build(truckBuilder);
car.say();
truck.say();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment