Builder Pattern
The construction process of complex objects is separated, so that different implementation methods of this abstract process can construct different objects (properties).
motivation
The builder pattern can separate a part from its assembly process and create a complex object step by step. Users only need to specify the type of complex object to get the object without knowing the specific construction details inside.
Applicable scenarios
-
When the algorithm for creating complex objects should be independent of the components of the object and how they are assembled.
-
When the construction process must allow different representations of the object being constructed.
structure
Code example
//Building objects using the Builder interface public class Director { private Builder builder; public Director(Builder builder) { this.builder = builder; } public Product constructA() { builder.buildPartA(); builder.buildPartB(); builder.buildPartC(); return builder.getProduct(); } public Product constructB() { builder.buildPartB(); builder.buildPartA(); builder.buildPartC(); return builder.getProduct(); } }
//Build an abstract interface for each part of a Product object public 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; } }
//Implement the interface of Builder to construct and assemble the parts of the product public class ConcreteBuilder extends Builder { @Override public void buildPartA() { System.out.println("A"); } @Override public void buildPartB() { System.out.println("B"); } @Override public void buildPartC() { System.out.println("C"); } }
//Constructed object public class Product { private String partA; private String partB; private String partC; //Omit getter, setter... Method }
public class Client{ public static void main(String[] args) { Builder builder = new ConcreteBuilder(); Director director = new Director(builder); //Different implementation methods can construct different representations Product product = director.construct(); System.out.println(); product = director.construct2(); } }
:ABC :BAC
summary
The builder pattern separates the construction process of a complex object. Different assembly methods can construct different representations, and separate the construction part and the representation part, which can control the construction process more precisely. The builder hides the internal structure of the product and how the product is assembled. Because the product is constructed through an abstract interface, only a new generator needs to be defined to build the product when changing the internal representation of the product.