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

5. private ArrayList items = new ArrayList();

6.

7.public void add(String item){

8.if (!items.contains(item)){

9. items.add(item);

10.}

11.}

12.public void add(String item, int position){

13.if (!items.contains(item)){

14. items.add(position, item);

15.}

16.}

17.public void remove(String item){

18.if (items.contains(item)){

19. items.remove(items.indexOf(item));

20.}

21.}

23.public int getNumberOfItems(){ return items.size(); }

24.public Iterator getIterator(){ return items.iterator(); }

25.public String getListName(){ return listName; }

26.public void setListName(String newListName){ listName = newListName; }

28.public String toString(){ return listName; }

29.}

Both classes can provide an Iterator, so it's straightforward to write code to move through their elements. ListPrinter shows how the Iterators could be used to print the contents of collections out in their String form.

The class has three methods: printToDoList, printToDoListCollection and printIteratingElement. In all

three methods, the iteration process is based around a very simple while loop.

Example A.70 ListPrinter.java

1.import java.util.Iterator;

2.import java.io.PrintStream;

3.public class ListPrinter{

4.public static void printToDoList(ToDoList list, PrintStream output){

5.Iterator elements = list.getIterator();

6.output.println(" List - " + list + ":");

7.while (elements.hasNext()){

8. output.println("\t" + elements.next());

9.}

10.}

12.public static void printToDoListCollection(ToDoListCollection lotsOfLists,

PrintStream output){

13.Iterator elements = lotsOfLists.getIterator();

14.output.println("\"To Do\" List Collection:");

15.while (elements.hasNext()){

16. printToDoList((ToDoList)elements.next(), output);

17.}

18.}

20.public static void printIteratingElement(Iterating element, PrintStream output){

21.output.println("Printing the element " + element);

22.Iterator elements = element.getIterator();

23.while (elements.hasNext()){

24.

Object currentElement = elements.next();

25.

if (currentElement instanceof Iterating){

26.

printIteratingElement((Iterating)currentElement, output);

27.

output.println();

28.

}

29.

else{

30.

output.println(currentElement);

31.

}

32.}

33.}

34.}

The method printIteratingElement best demonstrates the power of combining the Iterator pattern with polymorphism. Here, any class that implements Iterating can be printed in String form. The method makes no assumptions about the underlying collection structure except that it can produce an Iterator.

This example uses two support classes, DataCreator and DataRetriever, to produce a sample set of to-do lists and store them in a file.

254

Example A.71 DataCreator.java

1.import java.io.Serializable;

2.import java.io.ObjectOutputStream;

3.import java.io.FileOutputStream;

4.import java.io.IOException;

5.public class DataCreator{

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

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

9.String fileName;

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

11. fileName = args[0];

12.}else{

13. fileName = DEFAULT_FILE;

14.}

15.serialize(fileName);

16.}

17.

18.public static void serialize(String fileName){

19.try{

20. serializeToFile(createData(), fileName);

21.} catch (IOException exc){

22. exc.printStackTrace();

23.}

24.}

26.private static Serializable createData(){

27.ToDoListCollection data = new ToDoListCollectionImpl();

28.ToDoList listOne = new ToDoListImpl();

29.ToDoList listTwo = new ToDoListImpl();

30.ToDoList listThree = new ToDoListImpl();

31.listOne.setListName("Daily Routine");

32.listTwo.setListName("Programmer hair washing procedure");

33.listThree.setListName("Reading List");

34.listOne.add("Get up (harder some days than others)");

35.listOne.add("Brew cuppa Java");

36.listOne.add("Read JVM Times");

37.listTwo.add("Lather");

38.listTwo.add("Rinse");

39.listTwo.add("Repeat");

40.listTwo.add("(eventually throw a TooMuchHairConditioner exception)");

41.listThree.add("The complete annotated aphorisms of Duke");

42.listThree.add("How green was my Java");

43.listThree.add("URL, sweet URL");

44.data.add(listOne);

45.data.add(listTwo);

46.data.add(listThree);

47.return data;

48.}

49.

50.private static void serializeToFile(Serializable data, String fileName) throws IOException{

51.ObjectOutputStream serOut = new ObjectOutputStream(new FileOutputStream(fileName));

52.serOut.writeObject(data);

53.serOut.close();

54.}

55.}

Example A.72 DataRetriever.java

1.import java.io.File;

2.import java.io.FileInputStream;

3.import java.io.IOException;

4.import java.io.ObjectInputStream;

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.

}else{

16.

System.err.println("Unable to locate the file " + fileName);

17.

}

18.}catch (ClassNotFoundException exc){

19. exc.printStackTrace();

255

20.}catch (IOException exc){

21. exc.printStackTrace();

22.}

23.return returnValue;

24.}

25.}

RunPattern coordinates this example by loading the sample data, then calling the ListPrinter method printToDoListCollection to print all lists and their elements.

Example A.73 RunPattern.java

1.import java.io.File;

2.import java.io.IOException;

3.public class RunPattern{

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

5.System.out.println("Example for the Iterator pattern");

6.System.out.println(" This code sample demonstrates how an Iterator can enforce");

7.

System.out.println(" uniformity of processing for different collection

types.");

8.System.out.println(" In this case, there are two classes, ToDoListImpl and");

9.System.out.println(" ToDoListCollectionImpl, that have different storage needs.");

10.System.out.println(" ToDoListImpl uses an ArrayList to store its elements in");

11.System.out.println(" ordered form. The ToDoListCollectionImpl uses a HashMap,");

12.System.out.println(" since it must differentiate between ToDoListImpl objects by");

13.System.out.println(" their String identifiers.");

14.System.out.println();

15.System.out.println("Although the two classes use different underlying collections,");

16.System.out.println(" the ListPrinter class can use the Iterator produced by each");

17.System.out.println(" to print out a set of list contents.");

18.System.out.println();

19.

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

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

22.}

23.ToDoListCollection lists = (ToDoListCollection)(DataRetriever.

deserializeData("data.ser"));

24.

25.System.out.println("Lists retrieved. Printing out contents using the Iterator");

26.System.out.println();

27.ListPrinter.printToDoListCollection(lists, System.out);

28.}

29.}

256

Mediator

In this example, a Mediator manages communication among the panels of a graphical user interface. The basic design of this GUI uses one panel to select a Contact from a list, another panel to allow editing, and a third panel to show the current state of the Contact. The Mediator interacts with each panel, calling the appropriate methods to keep each part of the GUI up to date.

The class MediatorGui creates the main window and the three panels for the application. It also creates a mediator and matches it with the three child panels.

Example A.74 MediatorGui.java

1.import java.awt.Container;

2.import java.awt.event.WindowEvent;

3.import java.awt.event.WindowAdapter;

4.import javax.swing.BoxLayout;

5.import javax.swing.JButton;

6.import javax.swing.JFrame;

7.import javax.swing.JPanel;

8.public class MediatorGui{

9.private ContactMediator mediator;

11. public void setContactMediator(ContactMediator newMediator){ mediator = newMediator; }

12.

13.public void createGui(){

14.JFrame mainFrame = new JFrame("Mediator example");

15.Container content = mainFrame.getContentPane();

16.content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));

17.ContactSelectorPanel select = new ContactSelectorPanel(mediator);

18.ContactDisplayPanel display = new ContactDisplayPanel(mediator);

19.ContactEditorPanel edit = new ContactEditorPanel(mediator);

20.content.add(select);

21.content.add(display);

22.content.add(edit);

23.mediator.setContactSelectorPanel(select);

24.mediator.setContactDisplayPanel(display);

25.mediator.setContactEditorPanel(edit);

26.mainFrame.addWindowListener(new WindowCloseManager());

27.mainFrame.pack();

28.mainFrame.setVisible(true);

29.}

30.private class WindowCloseManager extends WindowAdapter{

31.public void windowClosing(WindowEvent evt){

32. System.exit(0);

33.}

34.}

35.}

36.

37.

The simplest of the GUI panels is the ContactDisplayPanel. It has a method called contactChanged that updates its display region with the values of the Contact argument.

Example A.75 ContactDisplayPanel.java

1.import java.awt.BorderLayout;

2.import javax.swing.JPanel;

3.import javax.swing.JScrollPane;

4.import javax.swing.JTextArea;

5.public class ContactDisplayPanel extends JPanel{

6.private ContactMediator mediator;

7.private JTextArea displayRegion;

8.

9.public ContactDisplayPanel(){

10.createGui();

11.}

12.public ContactDisplayPanel(ContactMediator newMediator){

13.setContactMediator(newMediator);

14.createGui();

15.}

16.public void createGui(){

17.setLayout(new BorderLayout());

18.displayRegion = new JTextArea(10, 40);

19.displayRegion.setEditable(false);

257