Iterator Pattern 3 : Iterator Pattern « Design Pattern « Java






Iterator Pattern 3

//[C] 2002 Sun Microsystems, Inc.---
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.io.File;
import java.io.IOException;

public class RunIteratorPattern {
    public static void main(String [] arguments){
        System.out.println("Example for the Iterator pattern");
        System.out.println(" This code sample demonstrates how an Iterator can enforce");
        System.out.println(" uniformity of processing for different collection types.");
        System.out.println(" In this case, there are two classes, ToDoListImpl and");
        System.out.println(" ToDoListCollectionImpl, that have different storage needs.");
        System.out.println(" ToDoListImpl uses an ArrayList to store its elements in");
        System.out.println(" ordered form. The ToDoListCollectionImpl uses a HashMap,");
        System.out.println(" since it must differentiate between ToDoListImpl objects by");
        System.out.println(" their String identifiers.");
        System.out.println();
        System.out.println("Although the two classes use different underlying collections,");
        System.out.println(" the ListPrinter class can use the Iterator produced by each");
        System.out.println(" to print out a set of list contents.");
        System.out.println();
        
        if (!(new File("data.ser").exists())){
            DataCreator.serialize("data.ser");
        }
        ToDoListCollection lists = (ToDoListCollection)(DataRetriever.deserializeData("data.ser"));
        
        System.out.println("Lists retrieved. Printing out contents using the Iterator");
        System.out.println();
        ListPrinter.printToDoListCollection(lists, System.out);
    }
}
interface Iterating extends Serializable {
  public Iterator getIterator();
}

class ToDoListImpl implements ToDoList {
  private String listName;

  private ArrayList items = new ArrayList();

  public void add(String item) {
    if (!items.contains(item)) {
      items.add(item);
    }
  }

  public void add(String item, int position) {
    if (!items.contains(item)) {
      items.add(position, item);
    }
  }

  public void remove(String item) {
    if (items.contains(item)) {
      items.remove(items.indexOf(item));
    }
  }

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

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

  public String getListName() {
    return listName;
  }

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

  public String toString() {
    return listName;
  }
}

interface ToDoListCollection extends Iterating {
  public void add(ToDoList list);

  public void remove(ToDoList list);

  public int getNumberOfItems();
}

interface ToDoList extends Iterating {
  public void add(String item);

  public void add(String item, int position);

  public void remove(String item);

  public int getNumberOfItems();

  public String getListName();

  public void setListName(String newListName);
}

class ListPrinter {
  public static void printToDoList(ToDoList list, PrintStream output) {
    Iterator elements = list.getIterator();
    output.println("  List - " + list + ":");
    while (elements.hasNext()) {
      output.println("\t" + elements.next());
    }
  }

  public static void printToDoListCollection(ToDoListCollection lotsOfLists,
      PrintStream output) {
    Iterator elements = lotsOfLists.getIterator();
    output.println("\"To Do\" List Collection:");
    while (elements.hasNext()) {
      printToDoList((ToDoList) elements.next(), output);
    }
  }

  public static void printIteratingElement(Iterating element,
      PrintStream output) {
    output.println("Printing the element " + element);
    Iterator elements = element.getIterator();
    while (elements.hasNext()) {
      Object currentElement = elements.next();
      if (currentElement instanceof Iterating) {
        printIteratingElement((Iterating) currentElement, output);
        output.println();
      } else {
        output.println(currentElement);
      }
    }
  }
}

class DataRetriever {
  public static Object deserializeData(String fileName) {
    Object returnValue = null;
    try {
      File inputFile = new File(fileName);
      if (inputFile.exists() && inputFile.isFile()) {
        ObjectInputStream readIn = new ObjectInputStream(
            new FileInputStream(fileName));
        returnValue = readIn.readObject();
        readIn.close();
      } else {
        System.err.println("Unable to locate the file " + fileName);
      }
    } catch (ClassNotFoundException exc) {
      exc.printStackTrace();
    } catch (IOException exc) {
      exc.printStackTrace();
    }
    return returnValue;
  }
}

class ToDoListCollectionImpl implements ToDoListCollection {
  private HashMap lists = new HashMap();

  public void add(ToDoList list) {
    if (!lists.containsKey(list.getListName())) {
      lists.put(list.getListName(), list);
    }
  }

  public void remove(ToDoList list) {
    if (lists.containsKey(list.getListName())) {
      lists.remove(list.getListName());
    }
  }

  public int getNumberOfItems() {
    return lists.size();
  }

  public Iterator getIterator() {
    return lists.values().iterator();
  }

  public String toString() {
    return getClass().toString();
  }
}

class DataCreator {
  private static final String DEFAULT_FILE = "data.ser";

  public static void main(String[] args) {
    String fileName;
    if (args.length == 1) {
      fileName = args[0];
    } else {
      fileName = DEFAULT_FILE;
    }
    serialize(fileName);
  }

  public static void serialize(String fileName) {
    try {
      serializeToFile(createData(), fileName);
    } catch (IOException exc) {
      exc.printStackTrace();
    }
  }

  private static Serializable createData() {
    ToDoListCollection data = new ToDoListCollectionImpl();
    ToDoList listOne = new ToDoListImpl();
    ToDoList listTwo = new ToDoListImpl();
    ToDoList listThree = new ToDoListImpl();
    listOne.setListName("Daily Routine");
    listTwo.setListName("Programmer hair washing procedure");
    listThree.setListName("Reading List");
    listOne.add("Get up (harder some days than others)");
    listOne.add("Brew cuppa Java");
    listOne.add("Read JVM Times");
    listTwo.add("Lather");
    listTwo.add("Rinse");
    listTwo.add("Repeat");
    listTwo.add("(eventually throw a TooMuchHairConditioner exception)");
    listThree.add("The complete annotated aphorisms of Duke");
    listThree.add("How green was my Java");
    listThree.add("URL, sweet URL");
    data.add(listOne);
    data.add(listTwo);
    data.add(listThree);
    return data;
  }

  private static void serializeToFile(Serializable data, String fileName)
      throws IOException {
    ObjectOutputStream serOut = new ObjectOutputStream(
        new FileOutputStream(fileName));
    serOut.writeObject(data);
    serOut.close();
  }
}


           
       








Related examples in the same category

1.Iterator pattern in JavaIterator pattern in Java