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

4.import java.io.IOException;

5.import java.io.ObjectInputStream;

6.import java.io.ObjectOutputStream;

7.import java.io.Serializable;

8.public class FileLoader{

9.public static Object loadData(File inputFile){

10.Object returnValue = null;

11.try{

12.

if (inputFile.exists()){

13.

if (inputFile.isFile()){

14.

ObjectInputStream readIn = new ObjectInputStream(new

15.

FileInputStream(inputFile));

returnValue = readIn.readObject();

16.

readIn.close();

17.

}else{

18.

System.err.println(inputFile + " is a directory.");

19.

}

20.

}else{

21.

System.err.println("File " + inputFile + " does not exist.");

22.

}

23.}catch (ClassNotFoundException exc){

24. exc.printStackTrace();

25.}catch (IOException exc){

26. exc.printStackTrace();

27.}

28.return returnValue;

29.}

30.public static void storeData(File outputFile, Serializable data){

31.try{

32.

ObjectOutputStream writeOut = new ObjectOutputStream(new

33.

FileOutputStream(outputFile));

writeOut.writeObject(data);

34.

writeOut.close();

35.}catch (IOException exc){

36. exc.printStackTrace();

37.}

38.}

39.}

The interface Address and its implementer AddressImpl provide storage for address objects in this example.

Example A.195 Address.java

1.import java.io.Serializable;

2.public interface Address extends Serializable{

3.public static final String EOL_STRING = System.getProperty("line.separator");

4.public static final String SPACE = " ";

5.public static final String COMMA = ",";

6.public String getAddress();

7.public String getType();

8.public String getDescription();

9.public String getStreet();

10.public String getCity();

11.public String getState();

12.public String getZipCode();

13.

14.public void setType(String newType);

15.public void setDescription(String newDescription);

16.public void setStreet(String newStreet);

17.public void setCity(String newCity);

18.public void setState(String newState);

19.public void setZipCode(String newZip);

20.}

Example A.196 AddressImpl.java

1.public class AddressImpl implements Address{

2.private String type;

3.private String description;

4.private String street;

5.private String city;

6.private String state;

7.private String zipCode;

8.public static final String HOME = "home";

9.public static final String WORK = "work";

11.public AddressImpl(){ }

12.public AddressImpl(String newDescription, String newStreet,

324

13.String newCity, String newState, String newZipCode){

14.description = newDescription;

15.street = newStreet;

16.city = newCity;

17.state = newState;

18.zipCode = newZipCode;

19.}

20.

21.public String getType(){ return type; }

22.public String getDescription(){ return description; }

23.public String getStreet(){ return street; }

24.public String getCity(){ return city; }

25.public String getState(){ return state; }

26.public String getZipCode(){ return zipCode; }

27.

28.public void setType(String newType){ type = newType; }

29.public void setDescription(String newDescription){ description = newDescription; }

30.public void setStreet(String newStreet){ street = newStreet; }

31.public void setCity(String newCity){ city = newCity; }

32.public void setState(String newState){ state = newState; }

33.public void setZipCode(String newZip){ zipCode = newZip; }

34.

35.public String toString(){

36.return description;

37.}

38.public String getAddress(){

39.return description + EOL_STRING + street + EOL_STRING +

40. city + COMMA + SPACE + state + SPACE + zipCode + EOL_STRING;

41.}

42.}

The DataCreator class creates a test file with a set of sample addresses.

Example A.197 DataCreator.java

1.import java.io.Serializable;

2.import java.io.ObjectOutputStream;

3.import java.io.FileOutputStream;

4.import java.io.IOException;

5.import java.util.ArrayList;

6.public class DataCreator{

7.private static final String DEFAULT_FILE = "data.ser";

9.public static void main(String [] args){

10.String fileName;

11.if (args.length == 1){

12. fileName = args[0];

13.}else{

14. fileName = DEFAULT_FILE;

15.}

16.serialize(fileName);

17.}

18.

19.public static void serialize(String fileName){

20.try{

21. serializeToFile(createData(), fileName);

22.} catch (IOException exc){

23. exc.printStackTrace();

24.}

25.}

27.private static Serializable createData(){

28.ArrayList items = new ArrayList();

29.items.add(new AddressImpl("Home address", "1418 Appian Way", "Pleasantville", "NH",

"27415"));

30.items.add(new AddressImpl("Resort", "711 Casino Ave.", "Atlantic City", "NJ",

"91720"));

31.items.add(new AddressImpl("Vacation spot", "90 Ka'ahanau Cir.", "Haleiwa", "HI",

"41720"));

32.return items;

33.}

34.

35.private static void serializeToFile(Serializable data, String fileName) throws

IOException {

36.ObjectOutputStream serOut = new ObjectOutputStream(new

FileOutputStream(fileName));

37.serOut.writeObject(data);

38.serOut.close();

325

39.}

40.}

RunPattern demonstrates how the proxy could work in practice. First, it creates an AddressBookProxy and adds several new Address objects to the Proxy. These new addresses will initially be stored locally. It is only when the example calls the method getAllAddresses that the Proxy will create an AddressBookImpl object and retrieve addresses stored in the file.

Example A.198 RunPattern.java

1.import java.io.File;

2.import java.io.IOException;

3.import java.util.ArrayList;

4.public class RunPattern{

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

6.System.out.println("Example for the Proxy pattern");

7.System.out.println();

8.System.out.println("This code will demonstrate the use of a Proxy to");

9.System.out.println(" provide functionality in place of its underlying");

10.System.out.println(" class.");

11.System.out.println();

12.

13.System.out.println(" Initially, an AddressBookProxy object will provide");

14.System.out.println(" address book support without requiring that the");

15.System.out.println(" AddressBookImpl be created. This could potentially");

16.System.out.println(" make the application run much faster, since the");

17.System.out.println(" AddressBookImpl would need to read in all addresses");

18.System.out.println(" from a file when it is first created.");

19.System.out.println();

20.

21.if (!(new File("data.ser").exists())){

22.DataCreator.serialize("data.ser");

23.}

24.System.out.println("Creating the AddressBookProxy");

25.AddressBookProxy proxy = new AddressBookProxy("data.ser");

26.System.out.println("Adding entries to the AddressBookProxy");

27.System.out.println("(this operation can be done by the Proxy, without");

28.System.out.println(" creating an AddressBookImpl object)");

29.proxy.add(new AddressImpl("Sun Education [CO]", "500 El Dorado Blvd.", "Broomfield", "CO",

"80020"));

30.proxy.add(new AddressImpl("Apple Inc.", "1 Infinite Loop", "Redwood City", "CA", "93741"));

31.System.out.println("Addresses created. Retrieving an address");

32.System.out.println("(since the address is stored by the Proxy, there is");

33.System.out.println(" still no need to create an AddressBookImpl object)");

34.System.out.println();

35.System.out.println(proxy.getAddress("Sun Education [CO]").getAddress());

36.System.out.println();

37.

38.System.out.println("So far, all operations have been handled by the Proxy,");

39.System.out.println(" without any involvement from the AddressBookImpl.");

40.System.out.println(" Now, a call to the method getAllAddresses will");

41.System.out.println(" force instantiation of AddressBookImpl, and will");

42.System.out.println(" retrieve ALL addresses that are stored.");

43.System.out.println();

44.

45.ArrayList addresses = proxy.getAllAddresses();

46.System.out.println("Addresses retrieved. Addresses currently stored:");

47.System.out.println(addresses);

48.}

49.}

326