Builder Pattern
2022-03-12
0. What is Builder Pattern?
Used to help use separate the construction of a complex object from its representation so that the same construction process can create different representations.
- generalize the construction process for different representations
- e.g., different text parsers
1. Implementation of Builder Pattern
Components & Steps
- Define a class object - complex object
- Add a builder interface
- Create a concrete builder class
- Implement a director class
class Program
{
static void Main(string[] args)
{
var items = new List<FurnitureItem>
{
new FurnitureItem("Sectional Couch", 55.5, 22.4, 78.6, 35.0),
new FurnitureItem("Nightstand", 25.0, 12.4, 20.0, 10.0),
new FurnitureItem("Dining Table", 105.0, 35.4, 100.6, 55.5),
};
// create an instance of the concrete class
var inventoryBuilder = new DailyReportBuilder(items);
// set up a director class
var director = new InventoryBuilderDirector(inventoryBuilder);
// use director to build the item
director.CreateReport();
// get the report from the concrete class
var directorReport = inventoryBuilder.GetDailyReport();
Console.WriteLine(directorReport.Debug());
}
}
Fluent Variation (not require director class)
- Define a class object - complex object
- Add a builder interface - note we need to change the interface signature
- Create a concrete builder class
class Program
{
static void Main(string[] args)
{
var items = new List<FurnitureItem>
{
new FurnitureItem("Sectional Couch", 55.5, 22.4, 78.6, 35.0),
new FurnitureItem("Nightstand", 25.0, 12.4, 20.0, 10.0),
new FurnitureItem("Dining Table", 105.0, 35.4, 100.6, 55.5),
};
// create an instance of the concrete class
var inventoryBuilder = new DailyReportBuilder(items);
// call methods directly to build object
// the fluent variation doesn't require a director class
var fluentReport = inventoryBuilder
.AddTitle()
.AddDimensions()
.AddLogistics(DateTime.UtcNow)
.GetDailyReport();
Console.WriteLine(fluentReport.Debug());
}
}
Summary
- This pattern isn’t for everything. It’s overkill for most classes where subclassing, refactoring, or abstracted interfaces or classes would be a better solution.
- If you have a finite number of related classes that perform the same general function, but with different representations, this is also going to qualify for the builder pattern.
- The builder pattern shares similarities with the factory pattern, builder pattern is focused on object creation in sequential steps, while the factory pattern is concerned with families or groups of objects being created.