DevIQ
Builder Design Pattern
Builder Design Pattern
The Builder design pattern is a creational pattern, similar to the Factory pattern (Factory Method, Abstract Factory). Unlike the Factory pattern, which typically only offers one method for creating an object, the Builder pattern offers multiple methods that can be used to gradually define the characteristics of the type to be created. This provides a more flexible interface than a single method with a large number of parameters or a complex parameter object.
A typical builder design (to create SomeType) has the following characteristics:
- Named SomeTypeBuilder to communicate the use of the pattern
- Initializes a simple (or default) private instance of SomeType upon construction
- Exposes methods that set properties on the private SomeType instance
- Each method returns this, the SomeTypeBuilder instance
- Exposes a Build (or Create) method that simply returns the private SomeType instance
- In some cases where creating SomeType is expensive, construction may be deferred to this step
- Optionally, expose (static) methods for getting known common configurations of SomeType
A simple example in C#
public class AddressBuilder{ private Address _address = new Address();
public AddressBuilder WithStreet(string street) { _address.Street = street; return this; } public AddressBuilder WithState(string state) { _address.State = state; return this; }
// additional WithWhatever methods
public Address Build() { return _address; }}
See Also
References
- Design Patterns Library (Pluralsight)
- Applying the Builder Pattern to an Angular Service (Typescript)
- Using Builder in C# Unit Tests Kata
- Flexible and Expressive Unit Tests with the Builder Pattern