The Builder Pattern
The Builder Pattern
Contextual Forces
Motivation
Separate the construction of a complex object from its representation so the same construction process can create different representations.
Encapsulation
Issues hidden from the consuming (Client) objects include:
- The construction process of each builder
- (possibly) Which builder is currently in use
- The number of builders that exist
- The nature of the complex object that a given builder creates
Procedural Analog
An automated build system, like Ant for example, is analogous to the Builder Pattern.
Non-Software Analog
Just in time book publishing is now a realistic option for major publishers and distributors such as Amazon.com, and large bookstores such as Powell's in Portland, Oregon. You simple feed in a digital file (PDF or similar) of the book in question, and the machine goes through multiple steps internally that results in a completely finished physical book emerging from the other end. The Builder does a very similar thing in software.
Implementation Forces
Example
A relational database contains information that can be consumed in different ways, depending on the needs of the client. Whereas one client might prefer to iterate over the data in a flat structure (like a Vector or ArrayList) another might need to see the data’s parent-child relationships implied by the foreign keys that records contain (which link them to other tables) a la the Composite Pattern. A builder would hide the details of construction, allowing the clients to specify which form of the data was desired without coupling to the specific steps required to make it.
Questions, concerns, credibility checks
There are different ways for the director to obtain the correct builder. The client may supply it, or the director may determine this based on the context of the application, etc… Sometimes another factory is used by the director to accomplish this. These issues must be dealt with on a case-by-case basis, as the nature of the problem domain will dictate what is correct in a given context. Because the different builders operate in sometimes vastly different ways, the performance of each may be inconsistent.
Options in implementation
Builder is typically implemented using other design patterns, Abstract Factor for example, depending on the nature of the sub-system being built. The Director in the Builder hides these details from the rest of the system.
Consequent Forces
Testing issues
The director can be tested using a Mock of the builder interface. Each individual builder can be tested in a straightforward way, the specifics depending on the nature of the complex object being built. For example, to determine how to test the Composite builder, one would refer to the Composite Pattern.
Cost-Benefit (gain-loss)
The builder increases design encapsulation, at the expense of some amount of performance degradation, depending on the nature of the individual builder elements themselves.