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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020