Patrón de constructor de TS
// The Builder pattern is a design pattern lets you construct complex
// objects step by step and it's used mainly in the object oriented
// programming paradigm.
// And you can implement the Builder pattern in Typescript is
// very easy and you can use the builder module.
class Builder {
public build() {
return new Product();
}
}
// Then you make a product class :
class Product {
constructor(private partA: string, private partB: string) {}
}
// Then you make a director class to build the builder:
class Director {
public build(builder: Builder) {
builder.buildPartA();
builder.buildPartB();
}
}
// Then you make a ConcreteBuilder that implements the Builder interface:
class ConcreteBuilder extends Builder {
private product: Product;
public buildPartA() {
this.product.partA = 'Part A';
}
public buildPartB() {
this.product.partB = 'Part B';
}
public getProduct() {
const product = this.product;
this.reset();
return product;
}
public reset() {
this.product = new Product('', '');
}
}
const builder = new ConcreteBuilder();
const director = new Director();
director.build(builder);
// make a new product
const product = new Product('Part A', 'Part B');
// get the product
const newProduct = builder.getProduct();
Puzzled Puffin