Main Page | See live article | Alphabetical index

Builder pattern

A software design pattern, the builder pattern is used to enable the creation of a variety of complex objects from one source object. The source object may consist of a variety of parts that contribute individually to the creation of each complex object through a set of common interface calls of the Abstract Builder class.

An example of a source object could be a list of characters and images in a message that is desired to be encoded. A director object is needed to feed information about the source object to the builder class. The abstract builder class would be a list of interface calls that the director will use like handleCharacter() or handleImage(). Each concrete version of the builder class could implement a method for these calls or just ignore the information if called. An example of a concrete Builder would be enigmaBuilder which might encrypt the text but ignore the images.

In the example above, the main software would create a specific Builder class, enigmaBuilder. This object would be passed to a simple Director object that would iterate through each piece of data in the main message of the source object. The builder class would incrementally create its final project. In the end, the main code will request the final object from the Builder and then destroy both the Builder and the Director. If there was a desire to replace the encryption technique of the enigmaBuilder with another one, a new Builder class could be substitued with little change to the director and main code since the only change would be the actual Builder object that would be given to the Director.

Oftentimes, builder pattern builds Composite pattern, a structure pattern.

Intent: Separate the construction of a complex object from its representation so that the same construction process can create different representations.

See also: ClassFactory, Adapter pattern, Abstract pattern, Laborer pattern