Java Reference
In-Depth Information
Builder (Chapter 15)
SOLUTION 15.1
The point of making the
Reservation
constructor
protected
is that it limits the ability to
instantiate your class. You want to compel other developers to create
Reservation
objects
with a builder rather than with the
Reservation
constructor. You could make
the constructor package protected, which would ensure that only other classes within your
package can construct
Reservation
objects. Making the constructor
protected
leaves
open the possibility of subclassing
Reservation
from another package. Note that making
the constructor's visibility
private
would break the builder classes' ability to instantiate
the
Reservation
class.
SOLUTION 15.2
The
build()
method of
UnforgivingBuilder
throws an exception if any attribute is
invalid and otherwise returns a valid
Reservation
object. Here is one implementation:
public Reservation build() throws BuilderException
{
if (date == null)
{
throw new BuilderException("Valid date not found");
}
if (city == null)
{
throw new BuilderException("Valid city not found");
}
if (headcount < MINHEAD)
{
throw new BuilderException(
"Minimum headcount is " + MINHEAD);
}
if (dollarsPerHead * headcount < MINTOTAL)
{
throw new BuilderException(
"Minimum total cost is " + MINTOTAL);
}
return new Reservation(
date,
headcount,
city,
dollarsPerHead,
hasSite);
}
Note that
UnforgivingBuilder
"inherits" constants, such as
MINHEAD
, from
the
ReservationConstants
interface.
SOLUTION 15.3
Here is one solution for a builder that creates a reasonable counteroffer from an incomplete
request: