The Builder

Intent: Separate the construction of a complex object from its representation so the same construction process can create different representations (Gamma et al., 1994).

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) in the composite pattern (see p. 26). 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.

images

Figure 4: Builder example diagram.

Qualities and Principles: Each builder has the single responsibility of building a specific version of the complex object that is needed. Clients couple to the interface of the director, but not the builders. A client is only concerned with the builder that applies to its needs. The other builders, their specifics, and their number are not referenced by a given client, and thus the design is open-closed to new builders that make new versions of the complex object. The director interface comes from the needs of the clients. The builder interface comes from the nature of the object being built.

Testing: The director can be tested using a mock (see p. 38) 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 (see p. 26).

Questions and Concerns: 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.

For more information: https://tinyurl.com/y3nmbkca

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset