Builder — RexDac Academy

RexDac AcademyTechnical notes · Some prior knowledge helps
0%Published notes read · this device

Principles and Architecture / Design patterns / Creational

Builder

Original notes by SunDiaL · View English source

The problem: You have an object that is always constructed the same way, but with optional features. The solution (if language permits): A constructor with optional parameters. The other solution: Create a Builder class that knows how to construct the object.

The builder is Indirection applied to the process of building.

Note 1: If step order matters, also create a Director class that uses a builder. Basically the Builder becomes a Strategy for the Director.

Note 2: You can have multiple builder classes that build the same thing in different ways.

public class House
{
	public Fence Fence { get; set; }
}

public class HouseBuilder
{
	private House house;
	
	public HouseBuilder()
	{
		this.house = new House();
	}
	
	public void Reset()
	{
		this.house = new House();
	}
	
	public void WithFence()
	{
		house.Fence = new Fence();
	}
	
	public House Build()
	{
		var result = this.house;
		this.Reset();
		return result;
	}
}