Overview
The Builder Design Pattern is used to construct a complex object step by step. It allows for creating different types and representations of an object using the same construction process.
Key Characteristics
- Encapsulates the construction of a product and allows it to be constructed in steps.
- Enables the creation of complex objects with different representations.
- Separates the creation logic from the representation.
Implementation
The following is an example of a Builder implementation in Java:
class Product {
private String partA;
private String partB;
private String partC;
public void setPartA(String partA) {
this.partA = partA;
}
public void setPartB(String partB) {
this.partB = partB;
}
public void setPartC(String partC) {
this.partC = partC;
}
@Override
public String toString() {
return "Product [PartA=" + partA + ", PartB=" + partB + ", PartC=" + partC + "]";
}
}
abstract class Builder {
protected Product product = new Product();
public abstract void buildPartA();
public abstract void buildPartB();
public abstract void buildPartC();
public Product getProduct() {
return product;
}
}
class ConcreteBuilder extends Builder {
@Override
public void buildPartA() {
product.setPartA("Part A");
}
@Override
public void buildPartB() {
product.setPartB("Part B");
}
@Override
public void buildPartC() {
product.setPartC("Part C");
}
}
class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public Product construct() {
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();
return builder.getProduct();
}
}
When to Use
- When the construction process of an object is complex.
- When an object needs to be created in a step-by-step process.
Advantages
- Provides control over the construction process.
- Allows for different representations of the same object.
Disadvantages
- Can add unnecessary complexity if the product is simple.