Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Builder

Pattern Properties

Type: Creational, Object
Level: Component

Purpose

To simplify complex object creation by defining a class whose purpose is to build instances of another class. The Builder produces one main product, such that there might be more than one class in the product, but there is always one main class.

Introduction

In a Personal Information Manager, users might want to manage a social calendar. To do this, you might define a class called Appointment to the information for a single event, and track information like the following:

  • Starting and ending dates
  • A description of the appointment
  • A location for the appointment
  • Attendees for the appointment

Naturally, this information is passed in by a user when he or she is setting up the appointment, so you define a constructor that allows you to set the state of a new Appointment object.

What exactly is needed to create an appointment, though? Different kinds of information are required depending on the specific type of the appointment. Some appointments might require a list of attendees (the monthly Monty Python film club meeting). Some might have start and end dates (JavaOne conference) and some might only have a single date—a plan to visit the art gallery for the M.C. Escher exhibit. When you consider these options, the task of creating an Appointment object is not trivial.

There are two possibilities for managing object creation, neither of them particularly attractive. You create constructors for every type of appointment you want to create, or you write an enormous constructor with a lot of functional logic. Each approach has its drawbacks—with multiple constructors, calling logic becomes more complex; with more functional logic built into the constructor, the code becomes more complex and harder to debug. Worse still, both approaches have the potential to cause problems if you later need to subclass Appointment.

Instead, delegate the responsibility of Appointment creation to a special AppointmentBuilder class, greatly simplifying the code for the Appointment itself. The AppointmentBuilder contains methods to create the parts of the Appointment, and you call the AppointmentBuilder methods that are relevant for the appointment type. Additionally, the AppointmentBuilder can ensure that the information passed in when creating the Appointment is valid, helping to enforce business rules. If you need to subclass Appointment, you either create a new builder or subclass the existing one. In either case, the task is easier than the alternative of managing object initialization through constructors.

Applicability

Use the Builder pattern when a class:

  • Has complex internal structure (especially one with a variable set of related objects).

  • Has attributes that depend on each other. One of the things a Builder can do is enforce staged construction of a complex object. This would be required when the Product attributes depend on one another. For instance, suppose you're building an order. You might need to ensure that you have a state set before you move on to "building" the shipping method, because the state would impact the sales tax applied to the Order itself.

  • 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 single point of creational control for its product, which other objects within the system can use. Like other creational patterns, this makes things easier for clients in the software system, since they need only access the Builder object to produce a resource.

The main drawback of this pattern is that there is tight coupling among the Builder, its product, and any other creational delegates used during object construction. Changes that occur for the product created by the Builder often result in modifications for both the Builder and its delegates.

Pattern Variants

At the most fundamental level, it is possible to implement a bare-bones Builder pattern around a single Builder class with a creational method and its product. For greater flexibility, designers often extend this base pattern with one or more of the following approaches:

  • Create an abstract Builder. By defining an abstract class or interface that specifies the creational methods, you can produce a more generic system that can potentially host many different kinds of builders.

  • Define multiple create methods for the Builder. Some Builders define multiple methods (essentially, they overload their creational method) to provide a variety of ways to initialize the constructed resource.

  • Develop creational delegates. With this variant, a Director object holds the overall Product create method and calls a series of more granular create methods on the Builder object. In this case, the Director acts as the manager for the Builder's creation process.

Related Patterns

Related patterns include Composite (page 157). The Builder pattern is often used to produce Composite objects, since they have a very complex structure.

Example

NOTE

For a full working example of this code example, with additional supporting classes and/or a RunPattern class, see "Builder" on page 343 of the "Full Code Examples" appendix.

This code example shows how to use the Builder pattern to create an appointment for the PIM. The following list summarizes each class's purpose:

  • AppointmentBuilder, MeetingBuilder – Builder classes

  • Scheduler – Director class

  • Appointment – Product

  • Address, Contact – Support classes, used to hold information relevant to the Appointment

  • InformationRequiredException – An Exception class produced when more data is required

For the base pattern, the AppointmentBuilder manages the creation of a complex product, an Appointment here. The AppointmentBuilder uses a series of build methods—buildAppointment, buildLocation, buildDates, and buildAttendees—to create an Appointment and populate it with data.

Example 1.10 AppointmentBuilder.java 0

 1. import java.util.Date;
 2. import java.util.ArrayList;
 3. 
 4. public class AppointmentBuilder{
 5.   
 6.   public static final int START_DATE_REQUIRED = 1;
 7.   public static final int END_DATE_REQUIRED = 2;
 8.   public static final int DESCRIPTION_REQUIRED = 4;
 9.   public static final int ATTENDEE_REQUIRED = 8;
10.   public static final int LOCATION_REQUIRED = 16;
11.   
12.   protected Appointment appointment;
13.   
14.   protected int requiredElements;
15.   
16.   public void buildAppointment(){
17.     appointment = new Appointment();
18.   }
19.   
20.   public void buildDates(Date startDate, Date endDate){
21.     Date currentDate = new Date();
22.     if ((startDate != null) && (startDate.after(currentDate))){
23.       appointment.setStartDate(startDate);
24.     }
25.     if ((endDate != null) && (endDate.after(startDate))){
26.       appointment.setEndDate(endDate);
27.     }
28.   }
29.   
30.   public void buildDescription(String newDescription){
31.     appointment.setDescription(newDescription);
32.   }
33.   
34.   public void buildAttendees(ArrayList attendees){
35.     if ((attendees != null) && (!attendees.isEmpty())){
36.       appointment.setAttendees(attendees);
37.     }
38.   }
39.   
40.   public void buildLocation(Location newLocation){
41.     if (newLocation != null){
42.       appointment.setLocation(newLocation);
43.     }
44.   }
45.   
46.   public Appointment getAppointment() throws InformationRequiredException{
47.     requiredElements = 0;
48.     
49.     if (appointment.getStartDate() == null){
50.       requiredElements += START_DATE_REQUIRED;
51.     }
52.     
53.     if (appointment.getLocation() == null){
54.       requiredElements += LOCATION_REQUIRED;
55.     }
56.     
57.     if (appointment.getAttendees().isEmpty()){
58.       requiredElements += ATTENDEE_REQUIRED;
59.     }
60.     
61.     if (requiredElements > 0){
62.       throw new InformationRequiredException(requiredElements);
63.     }
64.     return appointment;
65.   }
66.   
67.   public int getRequiredElements(){ return requiredElements; }
68. }

Example 1.11 Appointment.java 0

 1. import java.util.ArrayList;
 2. import java.util.Date;
 3. public class Appointment{
 4.   private Date startDate;
 5.   private Date endDate;
 6.   private String description;
 7.   private ArrayList attendees = new ArrayList();
 8.   private Location location;
 9.   public static final String EOL_STRING =
10.     System.getProperty("line.separator");
11.   
12.   public Date getStartDate(){ return startDate; }
13.   public Date getEndDate(){ return endDate; }
14.   public String getDescription(){ return description; }
15.   public ArrayList getAttendees(){ return attendees; }
16.   public Location getLocation(){ return location; }
17. 
18.   public void setDescription(String newDescription){ description = newDescription; }
19.   public void setLocation(Location newLocation){ location = newLocation; }
20.   public void setStartDate(Date newStartDate){ startDate = newStartDate; }
21.   public void setEndDate(Date newEndDate){ endDate = newEndDate; }
22.   public void setAttendees(ArrayList newAttendees){
23.     if (newAttendees != null){
24.       attendees = newAttendees;
25.     }
26.   }
27.   
28.   public void addAttendee(Contact attendee){
29.     if (!attendees.contains(attendee)){
30.       attendees.add(attendee);
31.     }
32.   }
33.   
34.   public void removeAttendee(Contact attendee){
35.     attendees.remove(attendee);
36.   }
37.   
38.   public String toString(){
39.     return " Description: " + description + EOL_STRING +
40.       " Start Date: " + startDate + EOL_STRING +
41.       " End Date: " + endDate + EOL_STRING +
42.       " Location: " + location + EOL_STRING +
43.       " Attendees: " + attendees;
44.   }
45. }

The Scheduler class makes calls to the AppointmentBuilder, managing the creation process through the method createAppointment.

Example 1.12 Scheduler.java0

 1. import java.util.Date;
 2. import java.util.ArrayList;
 3. public class Scheduler{
 4.   public Appointment createAppointment(AppointmentBuilder builder,
 5.     Date startDate, Date endDate, String description,
 6.     Location location, ArrayList attendees) throws InformationRequiredException{
 7.       if (builder == null){
 8.         builder = new AppointmentBuilder();
 9.       }
10.     builder.buildAppointment();
11.     builder.buildDates(startDate, endDate);
12.     builder.buildDescription(description);
13.     builder.buildAttendees(attendees);
14.     builder.buildLocation(location);
15.     return builder.getAppointment();
16.   }
17. }

The responsibilities of each class are summarized here:

  • Scheduler – Calls the appropriate build methods on AppointmentBuilder; returns a complete Appointment object to its caller.

  • AppointmentBuilder – Contains build methods and enforces business rules; creates the actual Appointment object.

  • Appointment – Holds information about an appointment.

The MeetingBuilder class in Example 1.13 demonstrates one of the benefits of the Builder pattern. To add additional rules for the Appointment, extend the existing builder. In this case, the MeetingBuilder enforces an additional constraint: for a meeting Appointment, start and end dates must be specified.

Example 1.13 MeetingBuilder.java 0

 1. import java.util.Date;
 2. import java.util.Vector;
 3. 
 4. public class MeetingBuilder extends AppointmentBuilder{
 5.   public Appointment getAppointment() throws InformationRequiredException{
 6.     try{
 7.       super.getAppointment();
 8.     }
 9.     finally{
10.       if (appointment.getEndDate() == null){
11.         requiredElements += END_DATE_REQUIRED;
12.       }
13.       
14.       if (requiredElements > 0){
15.         throw new InformationRequiredException(requiredElements);
16.       }
17.     }
18.     return appointment;
19.   }
20. }
  • + Share This
  • 🔖 Save To Your Account