Jump to content

Builder pattern

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Vishv.Malhotra (talk | contribs) at 03:50, 13 October 2021 (Added Java example of a builder pattern.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to separate the construction of a complex object from its representation. It is one of the Gang of Four design patterns.

Overview

The Builder design pattern is one of the GoF design patterns[1] that describe how to solve recurring design problems in object-oriented software.

The Builder design pattern solves problems like:[2]

  • How can a class (the same construction process) create different representations of a complex object?
  • How can a class that includes creating a complex object be simplified?

Creating and assembling the parts of a complex object directly within a class is inflexible. It commits the class to creating a particular representation of the complex object and makes it impossible to change the representation later independently from (without having to change) the class.

The Builder design pattern describes how to solve such problems:

  • Encapsulate creating and assembling the parts of a complex object in a separate Builder object.
  • A class delegates object creation to a Builder object instead of creating the objects directly.

A class (the same construction process) can delegate to different Builder objects to create different representations of a complex object.

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]

Advantages

Advantages of the Builder pattern include:[3]

  • Allows you to vary a product's internal representation.
  • Encapsulates code for construction and representation.
  • Provides control over steps of construction process.

Disadvantages

Disadvantages of the Builder pattern include:[3]

  • A distinct ConcreteBuilder must be created for each type of product.
  • Builder classes must be mutable.
  • May hamper/complicate dependency injection.

Structure

UML class and sequence diagram

A sample UML class and sequence diagram for the Builder design pattern.[4]

In the above UML class diagram, the Director class doesn't create and assemble the ProductA1 and ProductB1 objects directly. Instead, the Director refers to the Builder interface for building (creating and assembling) the parts of a complex object, which makes the Director independent of which concrete classes are instantiated (which representation is created). The Builder1 class implements the Builder interface by creating and assembling the ProductA1 and ProductB1 objects.
The UML sequence diagram shows the run-time interactions: The Director object calls buildPartA() on the Builder1 object, which creates and assembles the ProductA1 object. Thereafter, the Director calls buildPartB() on Builder1, which creates and assembles the ProductB1 object.

Class diagram

Builder Structure
Builder Structure
Builder
Abstract interface for creating objects (product).
ConcreteBuilder
Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.

Examples

A C# example:

/// <summary>
/// Represents a product created by the builder
/// </summary>
public class Bicycle
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int Height { get; set; }
    public string Colour { get; set; }

    public Bicycle(string make, string model, string colour, int height)
    {
        Make = make;
        Model = model;
        Colour = colour;
        Height = height;
    }
}

/// <summary>
/// The builder abstraction
/// </summary>
public interface IBicycleBuilder
{
    string Colour { get; set; }
    int Height { get; set; }

    Bicycle GetResult();
}

/// <summary>
/// Concrete builder implementation
/// </summary>
public class GTBuilder : IBicycleBuilder
{
    public string Colour { get; set; }
    public int Height { get; set; }

    public Bicycle GetResult()
    {
        return Height == 29 ? new Bicycle("GT", "Avalanche", Colour, Height) : null;        
    }
}

/// <summary>
/// The director
/// </summary>
public class MountainBikeBuildDirector
{
    private IBicycleBuilder _builder;
    public MountainBikeBuildDirector(IBicycleBuilder builder) 
    {
        _builder = builder;
    }

    public void Construct()
    {
        _builder.Colour = "Red";
        _builder.Height = 29;
    }

    public Bicycle getResult()
	{
		return this._builder.GetResult();
	}
}

public class Client
{
    public void DoSomethingWithBicycles()
    {
        var builder = new GTBuilder();
        var director = new MountainBikeBuildDirector(builder);

        // Director controls the stepwise creation of product and returns the result.
        director.Construct();
        Bicycle myMountainBike = director.GetResult();
    }
}

The Director assembles a bicycle instance in the example above, delegating the construction to a separate builder object that has been given to the Director by the Client.

/* 
 * Suppose we are give a bag of numbers and mathematical 
 * operators. The goal is to create an expression that 
 * evaluates to a given value.
 * 
 * Construction of expression is tricky and error prone.
 * However, the job is easily done by BUILDER pattern.
 * 
 * Example uses 10 digits as numbers and must use 9 binary
 * operators: 4 +, 3 *, 1 -, 1 /, and parentheses as needed.
 * We leave the target value to readers imagination for now!
 */
public class Director {
	public static void main(String[] args) {
		IExprBuilder bob = new ExprBuilder();
		/* Create atomic expressions */
		for (int i=0; i<10; i++)
			bob.buildAtomicExpr(Integer.toString(i));
		/* create a pile of available operators */
		bob.addSpare("+"); bob.addSpare("+"); 
		bob.addSpare("+"); bob.addSpare("+");
		bob.addSpare("*"); bob.addSpare("*");
		bob.addSpare("*"); bob.addSpare("-");
		bob.addSpare("/");
		
		/* Direct the Expression builder 
		 * Parameters are references to subexprs
		 */
		bob.buildExpr(8, 8, 9);
		bob.buildExpr(8, 6, 0);
		bob.buildExpr(4, 3, 5);
		bob.buildExpr(7, 4, 4);
		bob.buildExpr(6, 0, 2);
		bob.buildExpr(4, 2, 0);
		bob.buildExpr(1, 1, 2);
		bob.buildExpr(3, 7, 1);
		bob.buildExpr(1, 5, 0);
		System.out.println(bob.getResult());
	}
}

/* BUILDER INTERFACE
 * One can use the same interface for a post fix 
 * expression builder.
 * The same interfeace is good for evaluating expression 
 * instead of building it!
 */
public interface IExprBuilder {
	String getResult();
	void addSpare(String string);
	void buildAtomicExpr(String string);
	/* Combines two subexpressions by operator.
	 * Each operand is used EXACTLY once.
	 */
	int buildExpr(int rand1Idx, int operIdx, int rand2Idx);
}

public class ExprBuilder implements IExprBuilder {
	String[] expr;
	String operators[];
	int e; // Atomic expressions created
	int o; // Operators initially available

	public ExprBuilder() {
		expr = new String[10];
		operators = new String[9];
		e = o = 0;
	}

	@Override
	public void buildAtomicExpr(String atom) {
		expr[e] = atom;
		e++;
	}

	@Override
	public void addSpare(String oper) {
		operators[o] = oper;
		o++;
	}

	@Override
	public int buildExpr(int rand1, int opIdx, int rand2) {
		/*
		 * This builder is smart. It will avoid unneeded parentheses pairs.
		 */
		if (expr[rand1] == null || expr[rand2] == null || 
				operators[opIdx] == null) {
			System.out.println("Bad direction: Ignored");
			return -1;
		}

		if (operators[opIdx].equals("+") || expr[rand2].matches("[0-9]+")
				|| expr[rand2].charAt(0) == '(')
			/* Needs to enclosing parentheses pairs. */
			expr[rand1] = expr[rand1] + operators[opIdx] 
				+ expr[rand2];
		else
			expr[rand1] = expr[rand1] + operators[opIdx] 
					+ "(" + expr[rand2] + ")";
		operators[opIdx] = null;
		expr[rand2] = null; // Each expression is appears once
		if (rand1 < rand2) {
			return rand1; // composed expression is here
		} else { // Place new expression at lower index
			expr[rand2] = expr[rand1];
			expr[rand1] = null;
			return rand2;
		}
	}

	@Override
	public String getResult() {
		return expr[0];
	}
}

See also

References

  1. ^ a b Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 97ff. ISBN 0-201-63361-2.{{cite book}}: CS1 maint: multiple names: authors list (link)
  2. ^ "The Builder design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-13.
  3. ^ a b "Index of /archive/2010/winter/51023-1/presentations" (PDF). www.classes.cs.uchicago.edu. Retrieved 2016-03-03.
  4. ^ "The Builder design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017-08-12.