Pages

Sunday, September 23, 2012

builder pattern

Builder pattern is an object creation design pattern and it is used to build complex objects.
The builder design pattern has four elements

  1. Director : responsible for managing the creation of the object. It actually delegates the process to builder interface.
  2. Builder : An interface that describe how the parts of the objects are created.
  3. Product : The complex object to be created.
  4. Concrete Builder : implements the builder. Can have several builders that each describe how different type of object is created. 
The following example is taken from Wikipedia (http://en.wikipedia.org/wiki/Builder_pattern).



/** "Product" */
 class Pizza {
    private String dough = "";
    private String sauce = "";
    private String topping = "";
 
 
    public void setDough(String dough)     { this.dough = dough; }
    public void setSauce(String sauce)     { this.sauce = sauce; }
    public void setTopping(String topping) { this.topping = topping; }
 }
 
 
 /** "Abstract Builder" */
 abstract class PizzaBuilder {
    protected Pizza pizza;
 
    public Pizza getPizza() { return pizza; }
    public void createNewPizzaProduct() { pizza = new Pizza(); }
 
    public abstract void buildDough();
    public abstract void buildSauce();
    public abstract void buildTopping();
 }
 
 /** "ConcreteBuilder" */
 class HawaiianPizzaBuilder extends PizzaBuilder {
    public void buildDough()   { pizza.setDough("cross"); }
    public void buildSauce()   { pizza.setSauce("mild"); }
    public void buildTopping() { pizza.setTopping("ham+pineapple"); }
 }
 
 /** "ConcreteBuilder" */
 class SpicyPizzaBuilder extends PizzaBuilder {
    public void buildDough()   { pizza.setDough("pan baked"); }
    public void buildSauce()   { pizza.setSauce("hot"); }
    public void buildTopping() { pizza.setTopping("pepperoni+salami"); }
 }
 
 
 /** "Director" */
 class Waiter {
    private PizzaBuilder pizzaBuilder;
 
    public void setPizzaBuilder(PizzaBuilder pb) { pizzaBuilder = pb; }
    public Pizza getPizza() { return pizzaBuilder.getPizza(); }
 
    public void constructPizza() {
       pizzaBuilder.createNewPizzaProduct();
       pizzaBuilder.buildDough();
       pizzaBuilder.buildSauce();
       pizzaBuilder.buildTopping();
    }
 }
 
 
 /** A customer ordering a pizza. */
 class BuilderExample {
    public static void main(String[] args) {
        Waiter waiter = new Waiter();
        PizzaBuilder hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
        PizzaBuilder spicyPizzaBuilder = new SpicyPizzaBuilder();
 
        waiter.setPizzaBuilder( hawaiianPizzaBuilder );
        waiter.constructPizza();
 
        Pizza pizza = waiter.getPizza();
    }
 }

No comments:

Post a Comment