Simple Factory mode Abstract Factory mode Builder mode Factory Method mode Prototype mode Singleton mode Registry of Singleton Mode Problems
The builder pattern is a good choice when designing classes whose constructors or static factories wowould have more than a handful of parameters.
When there are many constructor parameters and multiple constructor functions, the following is the case:
Pizza(int size) { ... } Pizza(int size, boolean cheese) { ... } Pizza(int size, boolean cheese, boolean pepperoni) {...} Pizza(int size, boolean cheese, boolean pepperoni ,boolean bacon) { ... }
This is called the Telescoping Constructor Pattern. The following is a solution called the javabean mode:
Pizza pizza = new Pizza(12);pizza.setCheese(true);pizza.setPepperoni(true);pizza.setBacon(true);
Javabeans make a class mutable even if it is not strictly necessary. So javabeans require an extra effort in handling thread-safety (an immutable class is always thread safety !). For details, see JavaBean Pattern.
Build mode to solve this problemPublic class Pizza {// required private final int size; // optional private boolean cheese; private boolean pepperoni; private boolean bacon; public static class Builder {// required private final int size; // optional private boolean cheese = false; private boolean pepperoni = false; private boolean bacon = false; // this parameter is set to public Builder (int size) {this. size = size;} public Builder cheese (boolean value) {cheese = value; return this;} public Builder pepperoni (boolean value) {pepperoni = value; return this ;} public Builder bacon (boolean value) {bacon = value; return this;} public Pizza build () {return new Pizza (this) ;}} private Pizza (Builder builder) {size = builder. size; cheese = builder. cheese; pepperoni = builder. pepperoni; bacon = builder. bacon ;}}
Note that Pizza is an immutable class, so it is thread-safe. Because every Builder's setter method returns a Builder object, it can be called in tandem. As follows:
Pizza pizza = new Pizza.Builder(12) .cheese(true) .pepperoni(true) .bacon(true) .build();
As we can see above, the construction mode gives users greater freedom and can choose any parameter.