Creational Design Patterns-Builder
The next Creational Design Pattern up of discussion is the Builder Pattern. The Creational patterns are all about object creation and the Builder pattern is no different.
The pattern focuses on separating the methods for creating complex objects into their own constructs. The Client places their object requirements with what the pattern calls a Director. The Director’s role is to implement the build based on the client’s input. Thus separating the methods concerning reading and parsing from the product rendering Building methods.Thus allowing for the creation of complex objects with distinct renderings. In a nut shell, the Builder Pattern focuses on constructing a complex object step by step under the dictation of the director.
A real world example would be an assembly line in a car factory. Customer orders are passed to the assembly lead and the assemble line builds the required car according to the leads direction.
Take a look at the Java examples below.
Product & Builder
In this example we create our base product, Mustang. The Mustang class is an empty template of our car. All of it’s details are undefined. Following our product class we have the abstract Mustang Builder class. This class outlines all the step required to build our car. As an abstract you will notice there are still no details, those are prescribed in the builder implementations to follow.
Using our builder abstraction we now can create distinct build implementations of the mustang. All containing distinct features and details per build. This is the beauty that is the build pattern, parsing out complex products into separate targets for the clients consumption, depending solely on the directors invoking.
Director & Client
Our code now starts to come together with the sample Director and Client code above. You can see in this example the Dealer directs the required Mustang build based on our client’s request. Thus separating client input interpretation (director role) from the creation of our products. ( builder role).