Card 02/ 09

ConceptDifficulty: Intermediate1 min

Builder Pattern Structure: The Class Diagram

Builder, ConcreteBuilder, Product and the optional Director that runs the steps in order.

Builder has four participants: the builder interface, a concrete builder, the product it creates, and an optional director that calls the builder's steps in a fixed order. This card reads each role off the Gang of Four's class diagram and says why the director is usually missing from builders you will meet.

Builder participants
Each participant and its role
ParticipantRole
BuilderDeclares one step for each part and a build() that returns the product.
ConcreteBuilderStores the parts as they are set, and in build() checks them and creates the Product.
ProductThe finished object. It often has no setters, so it cannot change after build().
DirectorOptional. Calls the steps in a known order, so a common configuration is written once.

Read the diagram from the left. The director holds a builder through its interface, shown by the hollow diamond, and calls its steps. The concrete builder implements those steps and is the only class that creates the product, shown by the dashed arrow.

The Gang of Four drew the director as essential, because their builders produced different representations from the same steps: one director could drive a builder that wrote plain text or one that wrote formatted text. Most builders written now have one concrete builder and no interface, and the client calls the steps itself, in a chain. The director survives where a few fixed configurations are wanted, such as a minimal product and a full one.