Why would we need the director pattern? The builder can itself execute the whole construction process instead of going through the director.
class Pizza {
private String dough = "";
private String sauce = "";
private String topping = "";
public static abstract class Builder {
private Pizza pizza;
public Builder() {
pizza = new Pizza();
}
public abstract Builder buildDough();
public abstract Builder buildSauce();
public abstract Builder buildTopping();
public Pizza getPizza() {
return pizza;
}
protected void addTopping(String topping) {
pizza.topping = topping;
}
protected void addSauce(String string) {
pizza.sauce = string;
}
public void addDough(String dough) {
pizza.dough = dough;
}
}
}
class SpicyPizzaBuilder extends Pizza.Builder {
@Override
public SpicyPizzaBuilder buildDough() {
super.addDough("Pan Baked");
return this;
}
@Override
public SpicyPizzaBuilder buildSauce() {
super.addSauce("hot");
return this;
}
@Override
public SpicyPizzaBuilder buildTopping() {
super.addTopping("pepperoni+salami");
return this;
}
}
class HawaiianPizzaBuilder extends Pizza.Builder {
@Override
public Builder buildDough() {
super.addDough("cross");
return this;
}
@Override
public Builder buildSauce() {
super.addSauce("mild");
return this;
}
@Override
public Builder buildTopping() {
super.addTopping("ham+Pineabble");
return this;
}
}
class Cook {
private Pizza.Builder pizzaBuilder;
public void constructPizza() {
pizzaBuilder.buildDough().buildSauce().buildTopping();
}
public Pizza getPizza() {
return pizzaBuilder.getPizza();
}
public void setPizzaBuilder(Builder hawaiianPizzaBuilder) {
pizzaBuilder = hawaiianPizzaBuilder;
}
}
public class BuilderExample {
public static void main(String[] args) {
Pizza.Builder hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
Pizza.Builder spicyPizzaBuilder = new SpicyPizzaBuilder();
Cook cook = new Cook();
cook.setPizzaBuilder(hawaiianPizzaBuilder);
cook.constructPizza();
Pizza hawaiian = cook.getPizza();
cook.setPizzaBuilder(spicyPizzaBuilder);
cook.constructPizza();
Pizza spicy = cook.getPizza();
}
}
In the above example the builder class have all the elements (data/method members) to construct the pizza ie PizzaBuilder is knowledgeable and highly coupled with the pizza. Then why the need for an extra layer of complexity? So construct method could be moved from cook (director) into PizzaBuilder.