Builder Pattern

Role

The Builder pattern separates the specification of a complex object from its actual construction. The same construction process can create different representations.

Illustration

Following on from the replica bag example introduced in the previous section, suppose that an online order company offers bags and shoes—both real and replica—on a bespoke basis (i.e., with the products made to order). We would expect that the time taken to make one of the genuine articles would be longer. In addition, we would notice other differences between the products. Each bag (Product) is made up of several parts, including the outside material, the lining, the label, the handle, and so on. The genuine, more expensive bags will have more parts usually. Certainly, there can be differences in the part lists for different makes of bags. For example, apart from being plastic (not leather), a replica bag might not have a nice lining.

The Builder pattern goes into the details of how the products are actually made, and some of this information can be transmitted back to the customer. For example, the time taken to deliver will be obvious, but the country of origin as specified on the label might also be important.

Design

The Builder pattern is based on Directors and Builders. Any number of Builder classes can conform to an IBuilder interface, and they can be called by a director to produce a product according to specification. The builders supply parts that the Product objects accumulate ...

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.