Problem

Applications need to create the elements of a complex structure. Sometimes the specifications for such elements exist on a different device or storage medium than where they need to be created.

Solution

Separate the construction process so that different representations of the structure can be created. Add the ability to create several targets from a complex representation.

Related Patterns

Discussion

The focus of the Builder pattern is on creating complex aggregate structures. If many possible representations of a given common input are needed, then the abstraction gained from the Builder pattern will be very useful.

Examples

SmallTalk's ToolBuilder is a combination of the Builder and Abstract Factory patterns. Creating a kids meal at a fast food restaurant is a real-world example of the Builder pattern. The common input is the kids meal: each component can be customized by the customer to create a unique representation of the kids meal.

Code

This is a sample Burger Builder in C#. In this way, we can customize the Burger that is created by the Builder.

public class Burger{
  public Burger(){}
  public int Toppings{get; set;}
  public string Bun{get; set;}
}

public interface IBurgerBuilder{
  void SetBun([NotNull]string bun);
  void SetToppings([NotNull]int count);
  Burger GetResult();
}

public class BurgerBuilder: IBurgerBuilder{
  private Burger _burger;
  public BurgerBuilder(){this._burger = new Burger();}
  public void SetBun(string bun){this._burger.Bun = bun;}
  public void SetToppings(int count){this._burger.Toppings = count;}
  public Car GetResult(){return this._burger;}
}

public class BurgerBuildDirector{
  public Burger Construct(){
    BurgerBuilder builder = new BurgerBuilder();
    builder.setBun("Sesame");
    builder.setToppings(2);
    return builder.GetResult();
  }
}