Java Reference
In-Depth Information
Uses other objects in the system that might be difficult or inconvenient to obtain during creation.
Description
Because this pattern is concerned with building a complex object from possibly multiple different sources, it is
called the Builder. As object creation increases in complexity, managing object creation from within the
constructor method can become difficult. This is especially true if the object does not depend exclusively on
resources that are under its own control.
Business objects often fall into this category. They frequently require data from a database for initialization and
might need to associate with a number of other business objects to accurately represent the business model.
Another example is that of composite objects in a system, such as an object representing a drawing in a visual
editing program. Such an object might need to be related to an arbitrary number of other objects as soon as it's
created.
In cases like this, it is convenient to define another class (the Builder) that is responsible for the construction. The
Builder coordinates the assembly of the product object: creating resources, storing intermediate results, and
providing functional structure for the creation. Additionally, the Builder can acquire system resources required for
construction of the product object.
Implementation
The Builder class diagram is shown in Figure 1.2 .
Figure 1.2. Builder class diagram
To implement the Builder pattern, you need:
Director - Has a reference to an AbstractBuilder instance. The Director calls the creational methods on its
builder instance to have the different parts and the Builder build.
AbstractBuilder - The interface that defines the available methods to create the separate parts of the product.
ConcreteBuilder - Implements the AbstractBuilder interface. The ConcreteBuilder implements all the
methods required to create a real Product . The implementation of the methods knows how to process information
from the Director and build the respective parts of a Product . The ConcreteBuilder also has either a
getProduct method or a creational method to return the Product instance.
Product - The resulting object. You can define the product as either an interface (preferable) or class.
Benefits and Drawbacks
The Builder pattern makes it easier to manage the overall flow during the creation of complex objects. This
manifests itself in two ways:
For objects that require phased creation (a sequence of steps to make the object fully active), the Builder acts as a
higher-level object to oversee the process. It can coordinate and validate the creation of all resources and if
necessary provide a fallback strategy if errors occur.
For objects that need existing system resources during creation, such as database connections or existing business
objects, the Builder provides a convenient central point to manage these resources. The Builder also provides a
 
Search WWH ::




Custom Search