DEV Community

eidher
eidher

Posted on • Edited on

Builder Pattern

Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Alt Text

Participants

  • Builder: specifies an abstract interface for creating parts of a Product object
  • ConcreteBuilder: constructs and assembles parts of the product by implementing the Builder interface. Defines and keeps track of the representation it creates. Provides an interface for retrieving the product.
  • Director: constructs an object using the Builder interface
  • Product: represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled. Includes classes that define the constituent parts, including interfaces for assembling the parts into the final result.

Code

public class Main {

    public static void main(String[] args) {
        Director director = new Director();

        Builder b1 = new ConcreteBuilder1();
        Builder b2 = new ConcreteBuilder2();

        director.construct(b1);
        Product p1 = b1.getResult();
        p1.show();

        director.construct(b2);
        Product p2 = b2.getResult();
        p2.show();
    }
}

public class Director {

    public void construct(Builder builder) {
        builder.buildPartA();
        builder.buildPartB();
    }
}

public interface Builder {

    Product getResult();

    void buildPartA();

    void buildPartB();
}

public class ConcreteBuilder1 implements Builder {

    private Product product = new Product();

    @Override
    public Product getResult() {
        return product;
    }

    @Override
    public void buildPartA() {
        product.add("PartA");
    }

    @Override
    public void buildPartB() {
        product.add("PartB");
    }
}

public class ConcreteBuilder2 implements Builder {

    private Product product = new Product();

    @Override
    public Product getResult() {
        return product;
    }

    @Override
    public void buildPartA() {
        product.add("PartX");
    }

    @Override
    public void buildPartB() {
        product.add("PartY");
    }
}

public class Product {

    private List<String> parts = new ArrayList<>();

    public void show() {
        System.out.println("\nProduct Parts -------");
        for (String part : parts) {
            System.out.println(part);
        }
    }

    public void add(String part) {
        parts.add(part);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Product Parts -------
PartA
PartB

Product Parts -------
PartX
PartY

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.