Java Reference
In-Depth Information
Code that uses a builder will look something like the following:
package com.oozinoz.applications;
import com.oozinoz.reservation.*;
public class ShowUnforgiving
{
public static void main(String[] args)
{
String sample =
"Date, November 5, Headcount, 250, "
+ "City, Springfield, DollarsPerHead, 9.95, "
+ "HasSite, No";
ReservationBuilder b = new UnforgivingBuilder();
new ReservationParser(b).parse(sample);
try
{
Reservation r = b.build();
System.out.println(r);
}
catch (BuilderException e)
{
System.out.println(e.getMessage());
}
}
}
Running this program prints out a
Reservation
object:
Date: Nov 5, 2001, Headcount: 250, City: Springfield,
Dollars/Head: 9.95, Has Site: false
Given a reservation request string, the code instantiates a builder and a parser and asks the
parser to parse the string. As it reads the string, the parser passes the reservation attributes to
the builder, using the builder's
set
methods. (The parser is a bit off the topic of B
UILDER
, but
its code is available at oozinoz.com.)
After parsing, the code asks the builder to build a valid reservation. This example just prints
out an exception's message text rather than taking a more significant action as you would in a
real application.
CHALLENGE 15.2
The
build()
method of the
UnforgivingBuilder
class throws
a
BuilderException
if the date or city is null, if the headcount is too low, or if
the total cost of the proposed reservation is too low. Write the code for
the
build()
method according to these specifications.