ts Builder pattern

The solution for “ts Builder pattern” can be found here. The following code will assist you in solving the problem.

// 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();

Thank you for using DeclareCode; We hope you were able to resolve the issue.

More questions on [categories-list]

0
inline scripts encapsulated in