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

38.

ObjectOutputStream writeOut = new ObjectOutputStream(new

39.

FileOutputStream(outputFile));

writeOut.writeObject(data);

40.

writeOut.close();

41.}

42.catch (IOException exc){

43. exc.printStackTrace();

44.}

45.}

46.}

The RunPattern class demonstrates this pattern by creating CalendarHOPP and CalendarImpl objects. It uses the CalendarHOPP to perform a local call (getHost), then as a way to access the remote resources—the stored collection of appointments managed by the CalendarImpl object.

Example A.190 RunPattern.java

1.import java.util.Calendar;

2.import java.util.Date;

3.import java.util.ArrayList;

4.import java.io.IOException;

5.import java.rmi.RemoteException;

6.public class RunPattern{

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

8.public static void main(String [] arguments) throws RemoteException{

9.System.out.println("Example for the HOPP pattern");

10.System.out.println();

11.System.out.println("This example will use RMI to demonstrate the HOPP pattern.");

12.System.out.println(" In the sample, there will be two objects created,

CalendarImpl");

13.System.out.println(" and CalendarHOPP. The CalendarImpl object provides the true");

14.System.out.println(" server-side implementation, while the CalendarHOPP would be");

15.System.out.println(" a client or middle-tier representative. The CalendarHOPP

will");

16.System.out.println(" provide some functionality, in this case supplying the

hostname");

17.System.out.println(" in response to the getHost method.");

18.System.out.println();

19.System.out.println("Note: This example runs the rmiregistry, CalendarHOPP and

CalendarImpl");

20.System.out.println(" on the same machine.");

21.System.out.println();

22.

23.try{

24.

Process

p1

=

Runtime.getRuntime().exec("rmic CalendarImpl");

25.

Process

p2

=

Runtime.getRuntime().exec("rmic CalendarHOPP");

26.

p1.waitFor();

27.

p2.waitFor();

28.}

29.catch (IOException exc){

30.System.err.println("Unable to run rmic utility. Exiting application.");

31. System.exit(1);

32.}

33.catch (InterruptedException exc){

34.System.err.println("Threading problems encountered while using the rmic

utility.");

35.

}

36.

 

37.System.out.println("Starting the rmiregistry");

38.System.out.println();

39.Process rmiProcess = null;

40.try{

41. rmiProcess = Runtime.getRuntime().exec("rmiregistry");

42. Thread.sleep(15000);

43.}

44.catch (IOException exc){

45. System.err.println("Unable to start the rmiregistry. Exiting application.");

46. System.exit(1);

47.}

48.catch (InterruptedException exc){

49.System.err.println("Threading problems encountered when starting the

rmiregistry.");

50.

}

51.

 

52.System.out.println("Creating the CalendarImpl object, which provides the

server-side implementation.");

320

53.System.out.println("(Note: If the CalendarImpl object does not have a file containing

Appointments,");

54.System.out.println(" this call will produce an error message. This will not affect

the example.)");

55. CalendarImpl remoteObject = new CalendarImpl();

56.

57.System.out.println();

58.System.out.println("Creating the CalendarHOPP object, which provides client-side

functionality.");

59. CalendarHOPP localObject = new CalendarHOPP();

60.

61.System.out.println();

62.System.out.println("Getting the hostname. The CalendarHOPP will handle this method

locally.");

63.System.out.println("Hostname is " + localObject.getHost());

64.System.out.println();

65.

66.System.out.println("Creating and adding appointments. The CalendarHOPP will

forward");

67.System.out.println(" these calls to the CalendarImpl object.");

68.Contact attendee = new ContactImpl("Jenny", "Yip", "Chief Java Expert", "MuchoJava

LTD");

69.ArrayList contacts = new ArrayList();

70.contacts.add(attendee);

71.Location place = new LocationImpl("Albuquerque, NM");

72.localObject.addAppointment(new Appointment("Opening speeches at annual Java Guru's

dinner",

73. contacts, place, createDate(2001, 4, 1, 16, 0),

74. createDate(2001, 4, 1, 18, 0)), createDate(2001, 4, 1, 0, 0));

75.localObject.addAppointment(new Appointment("Java Guru post-dinner Cafe time",

76. contacts, place, createDate(2001, 4, 1, 19, 30),

77. createDate(2001, 4, 1, 21, 45)), createDate(2001, 4, 1, 0, 0));

78.System.out.println("Appointments added.");

79.System.out.println();

80.

81.System.out.println("Getting the Appointments for a date. The CalendarHOPP will

forward");

82.System.out.println(" this call to the CalendarImpl object.");

83.System.out.println(localObject.getAppointments(createDate(2001,Y 4, 1, 0, 0)));

84.} L85.

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

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

88.return dateCreator.getTime();

89.}

90.} E F

T

TEAM FLY PRESENTS

321

Proxy

An address book grows tremendously over a period of time, since it stores all professional and social contacts. In addition, users don't need the address book every time they use the PIM. They do need some kind of address book placeholder to act as a starting point for them to use for graphical purposes, however. This example uses the Proxy pattern to represent the address book.

AddressBook defines the interface for accessing the PIM address book. At the very least, it needs to have the ability to add new contacts and to retrieve and store addresses.

Example A.191 AddressBook.java

1.import java.io.IOException;

2.import java.util.ArrayList;

3.public interface AddressBook {

4.public void add(Address address);

5.public ArrayList getAllAddresses();

6.public Address getAddress(String description);

8.public void open();

9.public void save();

10.}

Retrieving the data for the address book might be very time-consuming, given the incredible popularity of the users. Therefore, the proxy should delay creation of the real address book for as long as possible. The proxy, represented by AddressBookProxy, has the responsibility for creating the address book— but only when absolutely necessary.

Example A.192 AddressBookProxy.java

1.import java.io.File;

2.import java.io.IOException;

3.import java.util.ArrayList;

4.import java.util.Iterator;

5.public class AddressBookProxy implements AddressBook{

6.private File file;

7.private AddressBookImpl addressBook;

8.private ArrayList localAddresses = new ArrayList();

10.public AddressBookProxy(String filename){

11.file = new File(filename);

12.}

13.

14.public void open(){

15.addressBook = new AddressBookImpl(file);

16.Iterator addressIterator = localAddresses.iterator();

17.while (addressIterator.hasNext()){

18. addressBook.add((Address)addressIterator.next());

19.}

20.}

22.public void save(){

23.if (addressBook != null){

24. addressBook.save();

25.} else if (!localAddresses.isEmpty()){

26.

open();

27.

addressBook.save();

28.}

29.}

31.public ArrayList getAllAddresses(){

32.if (addressBook == null) {

33. open();

34.}

35.return addressBook.getAllAddresses();

36.}

37.

38.public Address getAddress(String description){

39.if (!localAddresses.isEmpty()){

40.

Iterator addressIterator = localAddresses.iterator();

41.

while (addressIterator.hasNext()){

42.

AddressImpl address = (AddressImpl)addressIterator.next();

43.

if (address.getDescription().equalsIgnoreCase(description)){

44.

return address;

322

45.

}

46.

}

47.}

48.if (addressBook == null){

49. open();

50.}

51.return addressBook.getAddress(description);

52.}

53.

54.public void add(Address address){

55.if (addressBook != null){

56. addressBook.add(address);

57.} else if (!localAddresses.contains(address)){

58. localAddresses.add(address);

59.}

60.}

61.}

Note that the AddressBookProxy has its own ArrayList for addresses. If the user adds an address by calling the add method, the proxy can use its internal address book without using the real address book.

The AddressBookImpl class represents the real address book for a user. It is associated with a file that stores an ArrayList with all the user's addresses. AddressBookProxy would create an AddressBookImpl object only when it is needed—when a user called the method getAllAddresses, for example.

Example A.193 AddressBookImpl.java

1.import java.io.File;

2.import java.io.IOException;

3.import java.util.ArrayList;

4.import java.util.Iterator;

5.public class AddressBookImpl implements AddressBook {

6.private File file;

7.private ArrayList addresses = new ArrayList();

8.

9.public AddressBookImpl(File newFile) {

10.file = newFile;

11.open();

12.}

13.

14. public ArrayList getAllAddresses(){ return addresses; }

15.

16.public Address getAddress(String description){

17.Iterator addressIterator = addresses.iterator();

18.while (addressIterator.hasNext()){

19.

AddressImpl address = (AddressImpl)addressIterator.next();

20.

if (address.getDescription().equalsIgnoreCase(description)){

21.

return address;

22.

}

23.}

24.return null;

25.}

26.

27.public void add(Address address) {

28.if (!addresses.contains(address)){

29. addresses.add(address);

30.}

31.}

33.public void open(){

34.addresses = (ArrayList)FileLoader.loadData(file);

35.}

36.

37.public void save(){

38.FileLoader.storeData(file, addresses);

39.}

40.}

AddressBookImpl delegates the task of loading and saving files to a worker class called FileLoader. This class has methods to read and write Serializable objects to a file.

Example A.194 FileLoader.java

1.import java.io.File;

2.import java.io.FileInputStream;

3.import java.io.FileOutputStream;

323