Java Reference
In-Depth Information
4. import java.io.ObjectInputStream;
5.
6. public class DataRetriever{
7. public static Object deserializeData(String fileName){
8. Object returnValue = null;
9. try{
10. File inputFile = new File(fileName);
11. if (inputFile.exists() && inputFile.isFile()){
12. ObjectInputStream readIn = new ObjectInputStream(new
FileInputStream(fileName));
13. returnValue = readIn.readObject();
14. readIn.close();
15. }
16. else {
17. System.err.println("Unable to locate the file " + fileName);
18. }
19. }
20. catch (ClassNotFoundException exc){
21. exc.printStackTrace();
22.
23. }
24. catch (IOException exc){
25. exc.printStackTrace();
26.
27. }
28. return returnValue;
29. }
30. }
RunPattern demonstrates how the Strategy works by first creating a ContactList , then printing out its entries
with each of the two SummarizingStrategy objects.
Example A.116 RunPattern.java
1. import java.io.File;
2. public class RunPattern {
3. public static void main(String[] arguments){
4. System.out.println("Example for the Strategy pattern");
5. System.out.println();
6. System.out.println("This code uses two Strategy classes, NameSummarizer and
OrganizationSummarizer,");
7. System.out.println(" to provide a sorted, summarized list for a ContactList. The
ContactList object");
8. System.out.println(" maintains a collection of Contacts, and delegates the task of
representing");
9. System.out.println(" its information to an associated object which implements
SummarizingStrategy.");
10. System.out.println();
11.
12. System.out.println("Deserializing stored ContactList from the data.serfile");
13. System.out.println();
14. if (!(new File("data.ser").exists())){
15. DataCreator.serialize("data.ser");
16. }
17. ContactList list = (ContactList)(DataRetriever. deserializeData("data.ser"));
18.
19. System.out.println("Creating NameSummarizer for the ContactList");
20. System.out.println("(this Strategy displays only the last and first name,");
21. System.out.println(" and sorts the list by last name, followed by the first)");
22. list.setSummarizer(new NameSummarizer());
23.
24. System.out.println("Name Summarizer Output for the ContactList:");
25. System.out.println(list.summarize());
26. System.out.println();
27.
28. System.out.println("Creating OrganizationSummarizer for the ContactList");
29. System.out.println("(this Strategy displays the organization, followed by the first");
30. System.out.println(" and last name. It sorts by the organization, followed by last
name)");
31. list.setSummarizer(new OrganizationSummarizer());
32.
33. System.out.println("Organization Summarizer Output for the ContactList:");
34. System.out.println(list.summarize());
35. System.out.println();
36. }
37. }
38.
 
Search WWH ::




Custom Search