Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Applied Java™ Patterns - Stephen Stelting, Olav Maassen.pdf
Скачиваний:
204
Добавлен:
24.05.2014
Размер:
2.84 Mб
Скачать

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 A.12 Appointment.java

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.}

28.public void addAttendee(Contact attendee){

29.if (!attendees.contains(attendee)){

30. attendees.add(attendee);

31.}

32.}

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 A.13 Scheduler.java

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();

223

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;

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.

if (requiredElements > 0){

14.

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

224

1.import java.io.Serializable;

2.public interface Location extends Serializable {

3.public String getLocation();

4.public void setLocation(String newLocation);

5.}

Example A.17 LocationImpl.java

1.public class LocationImpl implements Location{

2.private String location;

3.

4.public LocationImpl(){ }

5.public LocationImpl(String newLocation){

6.location = newLocation;

7.}

8.

9. public String getLocation(){ return location; }

10.

11. public void setLocation(String newLocation){ location = newLocation; }

12.

13.public String toString(){ return location; }

14.}

Example A.18 Contact.java

1.import java.io.Serializable;

2.public interface Contact extends Serializable{

3.public static final String SPACE = " ";

4.public String getFirstName();

5.public String getLastName();

6.public String getTitle();

7.public String getOrganization();

8.

9.public void setFirstName(String newFirstName);

10.public void setLastName(String newLastName);

11.public void setTitle(String newTitle);

12.public void setOrganization(String newOrganization);

13.}

Example A.19 ContactImpl.java

1.public class ContactImpl implements Contact{

2.private String firstName;

3.private String lastName;

4.private String title;

5.private String organization;

6.

7.public ContactImpl(String newFirstName, String newLastName,

8.String newTitle, String newOrganization){

9. firstName = newFirstName;

10. lastName = newLastName;

11. title = newTitle;

12. organization = newOrganization;

13. }

14.

15.public String getFirstName(){ return firstName; }

16.public String getLastName(){ return lastName; }

17.public String getTitle(){ return title; }

18.public String getOrganization(){ return organization; }

20.public void setFirstName(String newFirstName){ firstName = newFirstName; }

21.public void setLastName(String newLastName){ lastName = newLastName; }

22.public void setTitle(String newTitle){ title = newTitle; }

23.public void setOrganization(String newOrganization){ organization = newOrganization; }

25.public String toString(){

26.return firstName + SPACE + lastName;

27.}

28.}

The RunPattern file executes this example. It demonstrates the use of the Builder pattern by creating three

separate Appointment objects using the AppointmentBuilder and MeetingBuilder.

Example A.20 RunPattern.java

1.import java.util.Calendar;

2.import java.util.Date;

3.import java.util.ArrayList;

225

4.public class RunPattern{

5.private static Calendar dateCreator = Calendar.getInstance();

7.public static void main(String [] arguments){

8.Appointment appt = null;

9.

10.System.out.println("Example for the Builder pattern");

11.System.out.println();

12.System.out.println("This example demonstrates the use of the Builder");

13.System.out.println("pattern to create Appointment objects for the PIM.");

14.System.out.println();

15.

16.System.out.println("Creating a Scheduler for the example.");

17.Scheduler pimScheduler = new Scheduler();

18.

19.System.out.println("Creating an AppointmentBuilder for the example.");

20.System.out.println();

21.AppointmentBuilder apptBuilder = new AppointmentBuilder();

22.try{

23.

System.out.println("Creating a new Appointment with an AppointmentBuilder");

24.

appt = pimScheduler.createAppointment(

25.

apptBuilder, createDate(2066, 9, 22, 12, 30),

26.

null, "Trek convention", new LocationImpl("Fargo, ND"),

27.

createAttendees(4));

28.

System.out.println("Successfully created an Appointment.");

29.

System.out.println("Appointment information:");

30.

System.out.println(appt);

31.

System.out.println();

32.}

33.catch (InformationRequiredException exc){

34.

printExceptions(exc);

35.

}

36.

 

37.System.out.println("Creating a MeetingBuilder for the example.");

38.MeetingBuilder mtgBuilder = new MeetingBuilder();

39.try{

40.System.out.println("Creating a new Appointment with a MeetingBuilder");

41. System.out.println("(notice that the same create arguments will produce");

42.System.out.println(" an exception, since the MeetingBuilder enforces a");

43.

System.out.println(" mandatory end date)");

44.

appt = pimScheduler.createAppointment(

45.

mtgBuilder, createDate(2066, 9, 22, 12, 30),

46.

null, "Trek convention", new LocationImpl("Fargo, ND"),

47.

createAttendees(4));

48.

System.out.println("Successfully created an Appointment.");

49.

System.out.println("Appointment information:");

50.

System.out.println(appt);

51.

System.out.println();

52.}

53.catch (InformationRequiredException exc){

54.

printExceptions(exc);

55.

}

56.

 

57.System.out.println("Creating a new Appointment with a MeetingBuilder");

58.System.out.println("(This time, the MeetingBuilder will provide an end date)");

59.try{

60.

appt = pimScheduler.createAppointment(

61.

mtgBuilder,

62.

createDate(2002, 4, 1, 10, 00),

63.

createDate(2002, 4, 1, 11, 30),

64.

"OOO Meeting",

65.

new LocationImpl("Butte, MT"),

66.

createAttendees(2));

67.

System.out.println("Successfully created an Appointment.");

68.

System.out.println("Appointment information:");

69.

System.out.println(appt);

70.

System.out.println();

71.}

72.catch (InformationRequiredException exc){

73. printExceptions(exc);

74.}

75.}

77.public static Date createDate(int year, int month, int day, int hour, int minute){

78.dateCreator.set(year, month, day, hour, minute);

79.return dateCreator.getTime();

80.}

81.

226

82.public static ArrayList createAttendees(int numberToCreate){

83.ArrayList group = new ArrayList();

84.for (int i = 0; i < numberToCreate; i++){

85. group.add(new ContactImpl("John", getLastName(i), "Employee (nonexempt)", "Yoyodyne Corporation"));

86.}

87.return group;

88.}

89.

90.public static String getLastName(int index){

91.String name = "";

92.switch (index % 6){

93.

case 0: name = "Worfin";

94.

break;

95.

case 1: name = "Smallberries";

96.

break;

97.

case 2: name = "Bigbootee";

98.

break;

99.

case 3: name = "Haugland";

100.

break;

101.case 4: name = "Maassen";

102. break;

103.case 5: name = "Sterling";

104. break;

105.}

106.return name;

107.}

108.

109.public static void printExceptions(InformationRequiredException exc){

110.int statusCode = exc.getInformationRequired();

111.

112.System.out.println("Unable to create Appointment: additional information is

required");

113.if ((statusCode & InformationRequiredException.START_DATE_REQUIRED) > 0){

114.System.out.println(" A start date is required for this appointment to be

complete.");

115.}

116.if ((statusCode & InformationRequiredException.END_DATE_REQUIRED) > 0){

117.System.out.println(" An end date is required for this appointment to be

complete.");

118.}

119.if ((statusCode & InformationRequiredException.DESCRIPTION_REQUIRED) > 0){

120.System.out.println(" A description is required for this appointment to be

complete.");

121.}

122.if ((statusCode & InformationRequiredException.ATTENDEE_REQUIRED) > 0){

123.System.out.println(" At least one attendee is required for this appointment to

be complete.");

124.}

125.if ((statusCode & InformationRequiredException.LOCATION_REQUIRED) > 0){

126.System.out.println(" A location is required for this appointment to be

complete.");

127.}

128.System.out.println();

129.}

130.}

227