Java Reference
In-Depth Information
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 A.14
demonstrates one of the benefits of using the Builder pattern. To add
additional rules for the
Appointment
, extend the existing builder. In this case, the
MeetingBuilder
enforces an
additional constraint: for an
Appointment
that is a meeting, both start and end dates must be specified.
Example A.14
MeetingBuilder.java
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. }
Support classes used for this example include the class
InformationRequiredException
and the interfaces
Location
and
Contact
. The
Address
and
Contact
interfaces are marker interfaces used to represent supporting
information for the
Appointment
in this example; their implementation is represented by the
LocationImpl
and
ContactImpl
classes.
Example A.15
InformationRequiredException.java
1. public class InformationRequiredException extends Exception{
2. private static final String MESSAGE = "Appointment cannot be created because further
information is required";
3. public static final int START_DATE_REQUIRED = 1;
4. public static final int END_DATE_REQUIRED = 2;
5. public static final int DESCRIPTION_REQUIRED = 4;
6. public static final int ATTENDEE_REQUIRED = 8;
7. public static final int LOCATION_REQUIRED = 16;
8. private int informationRequired;
9.
10. public InformationRequiredException(int itemsRequired){
11. super(MESSAGE);
12. informationRequired = itemsRequired;
13. }
14.
15. public int getInformationRequired(){ return informationRequired; }
16. }
Example A.16
Location.java