Jump to content

Builder pattern: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Added examples section
No edit summary
Line 3: Line 3:
The builder pattern has another benefit. It can be used for objects that contain flat data ([[HTML|html]] code, [[SQL]] query, [[X.509]] certificate...), that is to say, data that can't be easily edited. This type of data cannot be edited step by step and must be edited at once. The best way to construct such an object is to use a builder class.{{citation needed|date=July 2015}}
The builder pattern has another benefit. It can be used for objects that contain flat data ([[HTML|html]] code, [[SQL]] query, [[X.509]] certificate...), that is to say, data that can't be easily edited. This type of data cannot be edited step by step and must be edited at once. The best way to construct such an object is to use a builder class.{{citation needed|date=July 2015}}


Builder often builds a [[Composite_pattern|Composite]]. Often, designs start out using [[Factory_method_pattern|Factory Method]] (less complicated, more customizable, subclasses proliferate) and evolve toward [[Abstract factory pattern|Abstract Factory]], [[Prototype_pattern|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. Builders are good candidates for a [[fluent interface]].<ref>{{cite web|last1=Nahavandipoor|first1=Vandad|title=Swift Weekly - Issue 05 - The Builder Pattern and Fluent Interface|url=https://github.com/vandadnp/swift-weekly/blob/master/issue05/README.md|website=Github.com}}</ref>
Builder often builds a [[Composite_pattern|Composite]]. Often, designs start out using [[Factory_method_pattern|Factory Method]] (less complicated, more customizable, subclasses proliferate) and evolve toward [[Abstract factory pattern|Abstract Factory]], [[Prototype_pattern|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. Builders are good candidates for a [[fluent interface]].<ref>{{cite web|last1=Nahavandipoor|first1=Vandad|title=Swift Weekly - Issue 05 - The Builder Pattern and Fluent Interface|url=https://github.com/vandadnp/swift-weekly/blob/master/issue05/README.md|website=Github.com}}</ref>{{Better source|reason=Citation cites this Wikipedia page}}


==Definition==
==Definition==

Revision as of 00:25, 23 June 2016

The builder pattern is an object creation software design pattern. Unlike the abstract factory pattern and the factory method pattern whose intention is to enable polymorphism, the intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern[citation needed]. The telescoping constructor anti-pattern occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.

The builder pattern has another benefit. It can be used for objects that contain flat data (html code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. This type of data cannot be edited step by step and must be edited at once. The best way to construct such an object is to use a builder class.[citation needed]

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. Builders are good candidates for a fluent interface.[1][better source needed]

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. [2]

Advantages[3]

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

Disadvantages[3]

  • Requires creating a separate ConcreteBuilder for each different type of Product.

Structure

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.

Pseudocode

We have a Car class. The problem is that a car has many options. The combination of each option would lead to a huge list of constructors for this class. So we will create a builder class, CarBuilder. We will send to the CarBuilder each car option step by step and then construct the final car with the right options:

class Car is
  Can have GPS, trip computer and various numbers of seats.
  Can be a city car, a sports car, or a cabriolet.

class CarBuilder is
  method getResult() is
      output:  a Car with the right options
    Construct and return the car.

  method setSeats(number) is
      input:  the number of seats the car may have.
    Tell the builder the number of seats.

  method setCityCar() is
    Make the builder remember that the car is a city car.

  method setCabriolet() is
    Make the builder remember that the car is a cabriolet.

  method setSportsCar() is
    Make the builder remember that the car is a sports car.

  method setTripComputer() is
    Make the builder remember that the car has a trip computer.

  method unsetTripComputer() is
    Make the builder remember that the car does not have a trip computer.

  method setGPS() is
    Make the builder remember that the car has a global positioning system.

  method unsetGPS() is
    Make the builder remember that the car does not have a global positioning system.

Construct a CarBuilder called carBuilder
carBuilder.setSeats(2)
carBuilder.setSportsCar()
carBuilder.setTripComputer()
carBuilder.unsetGPS()
car := carBuilder.getResult()

Of course one could dispense with Builder and just do this:

car = new Car();
car.seats = 2;
car.type = CarType.SportsCar;
car.setTripComputer();
car.unsetGPS();
car.isValid();

So this indicates that the Builder pattern is more than just a means to limit constructor proliferation. It removes what could be a complex building process from being the responsibility of the user of the object that is built. It also allows for inserting new implementations of how an object is built without disturbing the client code.

Examples

C#

//Represents a product created by the builder
public class Car
{
    public Car()
    {
    }

    public int Wheels { get; set; }

    public string Colour { get; set; }
}

//The builder abstraction
public interface ICarBuilder
{
    // Adding NotNull attribute to prevent null input argument
    void SetColour([NotNull]string colour);

    // Adding NotNull attribute to prevent null input argument
    void SetWheels([NotNull]int count);

    Car GetResult();
}

//Concrete builder implementation
public class CarBuilder : ICarBuilder
{
    private Car _car;

    public CarBuilder()
    {
        this._car = new Car();
    }

    public void SetColour(string colour)
    {
        this._car.Colour = colour;
    }

    public void SetWheels(int count)
    {
        this._car.Wheels = count;
    }

    public Car GetResult()
    {
        return this._car;
    }
}

//The director
public class CarBuildDirector
{
    public Car Construct()
    {
        CarBuilder builder = new CarBuilder();

        builder.SetColour("Red");
        builder.SetWheels(4);

        return builder.GetResult();
    }
}

The Director assembles a car instance in the example above, delegating the construction to a separate builder object.

C++

////// Product declarations and inline impl. (possibly Product.h) //////
class Product{
	public:
		// use this class to construct Product
		class Builder;

	private:
		// variables in need of initialization to make valid object
		int i;
		float f;
		char c;

		// Only one simple constructor - rest is handled by Builder
		Product( const int i, const float f, const char c ) : i(i), f(f), c(c){}

	public:
		// Product specific functionality
		void print();
		void doSomething();
		void doSomethingElse();
};


class Product::Builder{
	private:
		// variables needed for construction of object of Product class
		int i;
		float f;
		char c;

	public:
		// default values for variables
		static const int defaultI = 1;
		static const float defaultF = 3.1415f;
		static const char defaultC = 'a';

		// create Builder with default values assigned
		// (in C++11 they can be simply assigned above on declaration instead)
		Builder() : i( defaultI ), f( defaultF ), c( defaultC ){}

		// sets custom values for Product creation
		// returns Builder for shorthand inline usage (same way as cout <<)
		Builder& setI( const int i ){ this->i = i; return *this; }
		Builder& setF( const float f ){ this->f = f; return *this; }
		Builder& setC( const char c ){ this->c = c; return *this; }

		// prepare specific frequently desired Product
		// returns Builder for shorthand inline usage (same way as cout <<)
		Builder& setProductP(){
			this->i = 42;
			this->f = -1.0f/12.0f;
			this->c = '@';

			return *this;
		}

		// produce desired Product
		Product build(){
			// here optionaly check variable consistency
			// and also if Product is buildable from given information

			return Product( this->i, this->f, this->c );
		}
};
///// Product implementation (possibly Product.cpp) /////
#include <iostream>

void Product::print(){
	using namespace std;

	cout << "Product internals dump:" << endl;
	cout << "i: " << this->i << endl;
	cout << "f: " << this->f << endl;
	cout << "c: " << this->c << endl;
}

void Product::doSomething(){}
void Product::doSomethingElse(){}
//////////////////// Usage of Builder (replaces Director from diagram)
int main(){
	// simple usage
	Product p1 = Product::Builder().setI(2).setF(0.5f).setC('x').build();
	p1.print(); // test p1

	// advanced usage
	Product::Builder b;
	b.setProductP();
	Product p2 = b.build(); // get Product P object
	b.setC('!'); // customize Product P
	Product p3 = b.build();
	p2.print(); // test p2
	p3.print(); // test p3
}

Java

public class StreetMap {
	private final Point origin;
	private final Point destination;

	private final Color waterColor;
	private final Color landColor;
	private final Color highTrafficColor;
	private final Color mediumTrafficColor;
	private final Color lowTrafficColor;

	public static class Builder {
		// Required parameters
		private final Point origin;
		private final Point destination;

		// Optional parameters - initialize with default values
		private Color waterColor         = Color.BLUE;
		private Color landColor          = new Color(30, 30, 30);
		private Color highTrafficColor   = Color.RED;
		private Color mediumTrafficColor = Color.YELLOW;
		private Color lowTrafficColor    = Color.GREEN;

		public Builder(Point origin, Point destination) {
			this.origin      = origin;
			this.destination = destination;
		}

		public Builder waterColor(Color color) {
			waterColor = color;
			return this;
		}

		public Builder landColor(Color color) {
			landColor = color;
			return this;
		}

		public Builder highTrafficColor(Color color) {
			highTrafficColor = color;
			return this;
		}

		public Builder mediumTrafficColor(Color color) {
			mediumTrafficColor = color;
			return this;
		}

		public Builder lowTrafficColor(Color color) {
			lowTrafficColor = color;
			return this;
		}

		public StreetMap build() {
			return new StreetMap(this);
		}

	}

	private StreetMap(Builder builder) {
		// Required parameters
		origin      = builder.origin;
		destination = builder.destination;

		// Optional parameters
		waterColor         = builder.waterColor;
		landColor          = builder.landColor;
		highTrafficColor   = builder.highTrafficColor;
		mediumTrafficColor = builder.mediumTrafficColor;
		lowTrafficColor    = builder.lowTrafficColor;
	}

	public static void main(String args[]) {
		StreetMap map = new StreetMap.Builder(new Point(50, 50), new Point(100,
				100)).landColor(Color.GRAY).waterColor(Color.BLUE.brighter())
				.build();
	}
}

PHP

abstract class GetterSetter
{
    public function __get($name)
    {
        $method = sprintf('get%s', ucfirst($name));

        if (!method_exists($this, $method)) {
            throw new Exception();
        }

        return $this->$method();
    }

    public function __set($name, $v)
    {
        $method = sprintf('set%s', ucfirst($name));

        if (!method_exists($this, $method)) {
            throw new Exception();
        }

        $this->$method($v);
    }
}

//Represents a product created by the builder
class Car extends GetterSetter
{
    private $wheels;
    private $colour;
    
    function __construct()
    {
        
    }

    public function setWheels($wheels) 
    { 
        $this->wheels = $wheels;
    }
    
    public function getWheels() 
    { 
        return $this->wheels;
    }

    public function setColour($colour) 
    { 
        $this->colour = $colour;
    }
    
    public function getColour() 
    { 
        return $this->colour;
    }
}

//The builder abstraction
interface ICarBuilder
{
    public function SetColour($colour);
    public function SetWheels($count);
    public function GetResult();
}

//Concrete builder implementation
class CarBuilder implements ICarBuilder
{
    private $_car;

    function __construct()
    {
        $this->_car = new Car();
    }

    public function SetColour($colour)
    {
        $this->_car->Colour = $colour;
    }

    public function SetWheels($count)
    {
        $this->_car->Wheels = $count;
    }

    public function GetResult()
    {
        return $this->_car;
    }
}

//The director
class CarBuildDirector
{
    public $builder;
    
    function __construct($color = "White", $wheels = 4)
    {
        $this->builder = new CarBuilder();

        $this->builder->SetColour($color);
        $this->builder->SetWheels($wheels);
    }
    
    public function GetResult()
    {
        return $this->builder->GetResult();
    }
}

See also

References

  1. ^ Nahavandipoor, Vandad. "Swift Weekly - Issue 05 - The Builder Pattern and Fluent Interface". Github.com.
  2. ^ Gang Of Four
  3. ^ a b "Index of /archive/2010/winter/51023-1/presentations" (PDF). www.classes.cs.uchicago.edu. Retrieved 2016-03-03.