Builder pattern

Builder pattern

The builder pattern is an object creation software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects. Often, the builder pattern is used to build products in accordance to the composite pattern, and structural pattern.

Contents

Definition

The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so, the same construction process can create different representations. [1]

Structure

Builder Structure

Builder
Abstract interface for creating objects (product).
Concrete Builder
Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.
Director
The Director class is responsible for managing the correct sequence of object creation. It receives a Concrete Builder as a parameter and executes the necessary operations on it.
Product
The final object that will be created by the Director using Builder.

Useful tips

  • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components are built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
  • Builders are good candidates for a fluent interface.

Examples

C#

using System;
 
namespace BuilderPattern
{
  // Builder - abstract interface for creating objects (the product, in this case)
  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();
  }
  // Concrete Builder - provides implementation for Builder; an object able to construct other objects.
  // Constructs and assembles parts to build the objects
  class HawaiianPizzaBuilder : PizzaBuilder
  {
    public override void BuildDough()
    {
      pizza.Dough = "cross";
    }
 
    public override void BuildSauce()
    {
      pizza.Sauce = "mild";
    }
 
    public override void BuildTopping()
    {
      pizza.Topping = "ham+pineapple";
    }
  }
  // Concrete Builder - provides implementation for Builder; an object able to construct other objects.
  // Constructs and assembles parts to build the objects
  class SpicyPizzaBuilder : PizzaBuilder
  {
    public override void BuildDough()
    {
      pizza.Dough = "pan baked";
    }
 
    public override void BuildSauce()
    {
      pizza.Sauce = "hot";
    }
 
    public override void BuildTopping()
    {
      pizza.Topping = "pepperoni + salami";
    }
  }
 
  // Director - responsible for managing the correct sequence of object creation.
  // . receives a Concrete Builder as a parameter and executes the necessary operations on it
  class Cook
  {
    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();
    }
  }
 
  // Product - The final object that will be created by the Director using Builder
  public class Pizza
  {
    private string _dough = string.Empty;
    private string _sauce = string.Empty;
    private string _topping = string.Empty;
 
    public string Dough
    {
      get { return _dough; }
      set { _dough = value; }
    }
 
    public string Sauce
    {
      get { return _sauce; }
      set { _sauce = value; }
    }
 
    public string Topping
    {
      get { return _topping; }
      set { _topping = value; }
    }
  }
 
  class Program
  {
    static void Main(string[] args)
    {
      PizzaBuilder hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
      Cook cook = new Cook();
      cook.SetPizzaBuilder(hawaiianPizzaBuilder);
      cook.ConstructPizza();
      // create the product
      Pizza hawaiian = cook.GetPizza();
 
      PizzaBuilder spicyPizzaBuilder = new SpicyPizzaBuilder();
      cook.SetPizzaBuilder(spicyPizzaBuilder);
      cook.ConstructPizza();
      // create another product
      Pizza spicy = cook.GetPizza();
    }
  }
 
}

Java

public class Pizza {
 
        private String dough;
        private String sauce;
        private String topping;
 
        public String getDough() {
                return dough;
        }
 
        public void setDough(String dough) {
                this.dough = dough;
        }
 
        public String getSauce() {
                return sauce;
        }
 
        public void setSauce(String sauce) {
                this.sauce = sauce;
        }
 
        public String getTopping() {
                return topping;
        }
 
        public void setTopping(String topping) {
                this.topping = topping;
        }
 
        Pizza(PizzaBuilder builder) {
                dough = builder.getDough();
                sauce = builder.getSauce();
                topping = builder.getTopping();
        }
 
        @Override
        public String toString() {
                return "Dough:"+dough +" Topping:"+topping+" Sauce:"+sauce;
        }
}
 
public class PizzaBuilder {
        String dough;
        String sauce;
        String topping;
 
        public String getDough() {
                return dough;
        }
 
        public String getSauce() {
                return sauce;
        }
 
        public String getTopping() {
                return topping;
        }
 
        public PizzaBuilder setDough(String dough) {
                this.dough = dough;
                return this;
        }
 
        public PizzaBuilder setSauce(String sauce) {
                this.sauce = sauce;
                return this;
        }
 
        public PizzaBuilder setTopping(String topping) {
                this.topping = topping;
                return this;
        }
 
        public Pizza build() {
                return new Pizza(this);
        }
}
 
public class PizzaBuilderExample {
        public static void main(String[] args) {
                PizzaBuilder hawaiianPizzaBuilder = new PizzaBuilder()
                                .setDough("cross").setTopping("ham+pineapple").setSauce("mild");
                Pizza hawaiianPizza = hawaiianPizzaBuilder.build();
                System.out.println("Hawaiian Pizza: "+hawaiianPizza);
        }
}

C++

#include <string>
#include <iostream>
 
using namespace std;
 
// "Product"
class Pizza {
        public:
                void setDough(const string& dough) {
                        this->dough = new string(dough);
                }
 
                void setSauce(const string& sauce) {
                        this->sauce = new string(sauce);
                }
 
                void setTopping(const string& topping) {
                        this->topping = new string(topping);
                }
 
                void open() const {
                        cout << "Pizza with " << *dough << " dough, " << *sauce << " sauce and "
                        << *topping << " topping. Mmm." << endl;
                }
 
        private:
                string* dough;
                string* sauce;
                string* topping;
};
 
// "Abstract Builder"
class PizzaBuilder {
        public:
                Pizza* getPizza() {
                        return pizza;
                }
 
                void createNewPizzaProduct() {
                        pizza = new Pizza();
                }
 
                virtual void buildDough() = 0;
                virtual void buildSauce() = 0;
                virtual void buildTopping() = 0;
 
        protected:
                Pizza* pizza;
};
 
//----------------------------------------------------------------
 
class HawaiianPizzaBuilder : public PizzaBuilder {
        public:
                void buildDough() {
                        pizza->setDough("cross");
                }
 
                void buildSauce() {
                        pizza->setSauce("mild");
                }
 
                void buildTopping() {
                        pizza->setTopping("ham+pineapple");
                }
};
 
class SpicyPizzaBuilder : public PizzaBuilder {
        public:
                void buildDough() {
                        pizza->setDough("pan baked");
                }
 
                void buildSauce() {
                        pizza->setSauce("hot");
                }
 
                void buildTopping() {
                        pizza->setTopping("pepperoni+salami");
                }
};
 
//----------------------------------------------------------------
 
class Cook {
        public:
                void setPizzaBuilder(PizzaBuilder* pizzaBuilder) {
                        this->pizzaBuilder = pizzaBuilder;
                }
 
                Pizza* getPizza() {
                        return pizzaBuilder->getPizza();
                }
 
                void constructPizza() {
                        pizzaBuilder->createNewPizzaProduct();
                        pizzaBuilder->buildDough();
                        pizzaBuilder->buildSauce();
                        pizzaBuilder->buildTopping();
                }
 
        private:
                PizzaBuilder* pizzaBuilder;
};
 
int main() {
        Cook cook;
        PizzaBuilder* hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
        PizzaBuilder* spicyPizzaBuilder = new SpicyPizzaBuilder();
 
        cook.setPizzaBuilder(hawaiianPizzaBuilder);
        cook.constructPizza();
 
        Pizza* hawaiian = cook.getPizza();
        hawaiian->open();
 
        cook.setPizzaBuilder(spicyPizzaBuilder);
        cook.constructPizza();
 
        Pizza* spicy = cook.getPizza();
        spicy->open();
 
        delete hawaiianPizzaBuilder;
        delete spicyPizzaBuilder;
        delete hawaiian;
        delete spicy;
}

References

  1. ^ Gang Of Four

External links


Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать курсовую

Look at other dictionaries:

  • Builder — can mean any of the following: *General contractor or Subcontractor that specializes in building work *Construction worker who specializes in building work *Builders Energy, an oil and gas services company based in Calgary, Alberta, Canada.… …   Wikipedia

  • Factory method pattern — Factory method in UML Facto …   Wikipedia

  • Design Pattern — Patron de conception Pour les articles homonymes, voir Patron. Un patron de conception (design pattern en anglais) est un concept de génie logiciel destiné à résoudre les problèmes récurrents suivant le paradigme objet. En français on utilise… …   Wikipédia en Français

  • Design pattern — Patron de conception Pour les articles homonymes, voir Patron. Un patron de conception (design pattern en anglais) est un concept de génie logiciel destiné à résoudre les problèmes récurrents suivant le paradigme objet. En français on utilise… …   Wikipédia en Français

  • Factory pattern — See also Factory method pattern The Factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects. The creation of an object often requires complex processes not… …   Wikipedia

  • Creational pattern — In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems… …   Wikipedia

  • Prototype pattern — The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to: avoid subclasses of an …   Wikipedia

  • Software design pattern — In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a… …   Wikipedia

  • Singleton pattern — In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to… …   Wikipedia

  • Singleton Pattern — Das Singleton (auch Einzelstück genannt) ist ein in der Softwareentwicklung eingesetztes Entwurfsmuster und gehört zur Kategorie der Erzeugungsmuster (engl. Creational Patterns). Es verhindert, dass von einer Klasse mehr als ein Objekt erzeugt… …   Deutsch Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”