- Published on
Builder Pattern
- Authors
- Name
- Khánh
Builder
- There are many variations for one type; instead of passing parameters to the constructor, using a builder is more convenient.
Steps to use the builder:
- Create an interface for the object (Car).
- Create an interface for the builder (CarBuilderStructure).
- Create a class implementing the Builder interface (CarBuilder).
- Create factories for each type of Car (Jeep, Sedan, etc.).
Examples
// 1. Create an interface for the object (Car).
interface Car {
name: string;
seats?: number;
engine?: string;
gps?: boolean;
tripComputer?: boolean;
}
// 2. Create an interface for the builder (CarBuilderStructure).
interface CarBuilderStructure {
showInfo: () => void;
setSeats: (seats: number) => void;
setEngine: (engine: string) => void;
setGPS: (hasGps: boolean) => void;
setTripComputer: (hasTripComputer: boolean) => void;
reset: () => void;
}
// 3. Create a class implementing the Builder interface (CarBuilder).
class CarBuilder implements CarBuilderStructure {
private car: Car;
constructor(name: string) {
this.car = { name };
}
setSeats(seats: number) {
this.car.seats = seats;
return this;
}
setEngine(engine: string) {
this.car.engine = engine;
return this;
}
setGPS(hasGps: boolean) {
this.car.gps = hasGps;
return this;
}
setTripComputer(hasTripComputer: boolean) {
this.car.tripComputer = hasTripComputer;
return this;
}
showInfo() {
return console.log(
`${this.car.name} - seats: ${this.car.seats}, engine: ${this.car.engine}, gps: ${this.car.gps}, tripComputer: ${this.car.tripComputer}`
);
}
reset() {
this.car = { name: this.car.name };
}
}
// 4. Create factories for each type of Car (Jeep, Sedan, etc.).
class JeepCarFactory {
constructor() {
const car = new CarBuilder("Jeep")
.setSeats(4)
.setGPS(true)
.setTripComputer(true);
car.showInfo();
return car;
}
}
class SedanCarFactory {
constructor() {
const car = new CarBuilder("Sedan")
.setSeats(4)
.setGPS(false)
.setTripComputer(true);
car.showInfo();
return car;
}
}
const sedan = new SedanCarFactory();
const jeep = new JeepCarFactory();