Java Reference
In-Depth Information
Chapter 15. Builder
The builder pattern moves the construction logic for an object outside the class to instantiate.
Making this move might be useful for several reasons. You might simply want to reduce
the size of a class that has many methods. You may also want to allow step-by-step
construction of a target object. This occurs when you acquire the parameters for a constructor
gradually, as happens with parsers and may happen with a user interface.
Building from a Parser
In addition to manufacturing fireworks, Oozinoz puts on fireworks displays. Travel agencies
e-mail their reservation requests in the form
Date, November 5, Headcount, 250, City, Springfield,
DollarsPerHead, 9.95, HasSite, No
As you might guess, this protocol originated in the days before XML ( Extensible Markup
Language ), but it has thus far proved sufficient. The request tells when a potential customer
wants to see a display and in what city. The request also specifies the minimum headcount
that the customer will guarantee and the amount of money per guest that the customer will
pay. The customer in this example wants to put on a show for 250 guests and is willing to pay
$9.95 per guest, or a total of $2,487.50. The travel agent has also indicated that the customer
does not have a site in mind for the display.
The task at hand is to parse the textual request and create a Reservation object that
represents it. We might approach this task by creating an empty Reservation object and
setting its parameters as our parser encounters them. This causes the problem that a given
Reservation object may or may not represent a valid request. For example, we might
finish reading the text of a request and then realize that it lacks a date.
To ensure that Reservation objects are always valid requests, we can use
a ReservationBuilder class. The ReservationBuilder object can store
a reservation request's attributes as a parser finds them and then build a Reservation
object, verifying its validity. Figure 15.1 shows the classes we need for this design.
Search WWH ::




Custom Search