Java/Design Pattern/Iterator Pattern

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

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();
  }
}





Iterator pattern in Java

/*
The Design Patterns Java Companion
Copyright (C) 1998, by James W. Cooper
IBM Thomas J. Watson Research Center
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class IterDemo extends JFrame implements ActionListener {
  JawtList kidList, kidClubList;
  JTextField tx;
  JButton Get;
  KidData kdata;
  public IterDemo() {
    super("Enumeration demo");
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    JPanel jp = new JPanel();
    getContentPane().add(jp);
    jp.setLayout(new GridLayout(1, 2));
    JPanel left = new JPanel();
    JPanel right = new JPanel();
    jp.add(left);
    jp.add(right);
    left.setBorder(new EmptyBorder(5, 5, 5, 5));
    right.setBorder(new EmptyBorder(5, 5, 5, 5));
    kidList = new JawtList(20);
    left.setLayout(new BorderLayout());
    left.add("Center", kidList);
    right.setLayout(new BorderLayout());
    tx = new JTextField(10);
    Get = new JButton("Get");
    Get.addActionListener(this);
    JPanel rtop = new JPanel();
    right.add("North", rtop);
    rtop.add(tx);
    rtop.add(Get);
    kidClubList = new JawtList(20);
    right.add("Center", kidClubList);
    kdata = new KidData("50free.txt");
    fillKidList();
    setSize(new Dimension(400, 300));
    setVisible(true);
  }
  //---------------------------------------
  private void fillKidList() {
    Enumeration ekid = kdata.elements();
    while (ekid.hasMoreElements()) {
      Kid k = (Kid) ekid.nextElement();
      kidList.add(k.getFrname() + " " + k.getLname());
    }
  }
  //---------------------------------------
  public void actionPerformed(ActionEvent e) {
    String club = tx.getText();
    if (club.trim().length() > 0) {
      Enumeration eclub = kdata.kidsInClub(club);
      while (eclub.hasMoreElements()) {
        Kid k = (Kid) eclub.nextElement();
        kidClubList.add(k.getFrname() + " " + k.getLname());
      }
    }
  }
  //---------------------------------------
  static public void main(String argv[]) {
    new IterDemo();
  }
}
interface awtList
{
     public void add(String s);
     public void remove(String s);
     public String[] getSelectedItems();
}

class JawtList extends JScrollPane implements ListSelectionListener, awtList {
  private JList listWindow;
  private JListData listContents;
  //-----------------------------------------
  public JawtList(int rows) {
    listContents = new JListData();
    listWindow = new JList(listContents);
    listWindow.setPrototypeCellValue("Abcdefg Hijkmnop");
    getViewport().add(listWindow);
  }
  //-----------------------------------------
  public void add(String s) {
    listContents.addElement(s);
  }
  //-----------------------------------------
  public void remove(String s) {
    listContents.removeElement(s);
  }
  //-----------------------------------------
  public void clear() {
    listContents.clear();
  }
  //-----------------------------------------
  public String[] getSelectedItems() {
    Object[] obj = listWindow.getSelectedValues();
    String[] s = new String[obj.length];
    for (int i = 0; i < obj.length; i++)
      s[i] = obj[i].toString();
    return s;
  }
  //-----------------------------------------
  public void valueChanged(ListSelectionEvent e) {
  }
}
//=========================================
class JListData extends AbstractListModel {
  private Vector data;
  //-----------------------------------------
  public JListData() {
    data = new Vector();
  }
  //-----------------------------------------
  public int getSize() {
    return data.size();
  }
  //-----------------------------------------
  public Object getElementAt(int index) {
    return data.elementAt(index);
  }
  //-----------------------------------------
  public void addElement(String s) {
    data.addElement(s);
    fireIntervalAdded(this, data.size() - 1, data.size());
  }
  //-----------------------------------------
  public void removeElement(String s) {
    data.removeElement(s);
    fireIntervalRemoved(this, 0, data.size());
  }
  //-----------------------------------------
  public void clear() {
    int size = data.size();
    data = new Vector();
    fireIntervalRemoved(this, 0, size);
  }
}
class KidData {
  Vector kids;
  //------------------------------------------
  public KidData(String filename) {
    kids = new Vector();
    InputFile f = new InputFile(filename);
    String s = f.readLine();
    while (s != null) {
      if (s.trim().length() > 0) {
        Kid k = new Kid(s);
        kids.addElement(k);
      }
      s = f.readLine();
    }
  }
  //--------------------------------
  public Kid[] getData() {
    Kid[] kd = new Kid[kids.size()];
    for (int i = 0; i < kids.size(); i++)
      kd[i] = (Kid) kids.elementAt(i);
    return kd;
  }
  //--------------------------------
  public Enumeration elements() {
    return kids.elements();
  }
  //-------------------------------
  public Enumeration kidsInClub(String club) {
    return new kidClub(this, club);
  }
  //--------------------------------
  public int size() {
    return kids.size();
  }
  //--------------------------------
  public Kid getKid(int i) {
    return (Kid) kids.elementAt(i);
  }
  //--------------------------------
  public Vector getKidData(int key) {
    Vector v = new Vector();
    for (int i = 0; i < kids.size(); i++)
      v.addElement(getKid(i).getData(key));
    return v;
  }
  //--------------------------------
  public int getTableKey(String tabName) {
    int key = -1;
    tabName = tabName.toLowerCase();
    if (tabName.equals("frname"))
      key = ParseVar.FRNAME;
    if (tabName.equals("lname"))
      key = ParseVar.LNAME;
    if (tabName.equals("age"))
      key = ParseVar.AGE;
    if (tabName.equals("club"))
      key = ParseVar.CLUB;
    if (tabName.equals("time"))
      key = ParseVar.TIME;
    return key;
  }
  //----------------------------
  public String getTableName(int i) {
    String name = "";
    switch (i) {
    case ParseVar.FRNAME:
      name = "frname";
    case ParseVar.LNAME:
      name = "lname";
    case ParseVar.AGE:
      name = "age";
    case ParseVar.CLUB:
      name = "club";
    case ParseVar.TIME:
      name = "time";
    }
    return name;
  }
  //----------------------------
}
class ParseObject {
  public static final int VERB = 1000, VAR = 1010, MULTVAR = 1020;
  protected int value;
  protected int type;
  public int getValue() {
    return value;
  }
  public int getType() {
    return type;
  }
}
class ParseVar extends ParseObject {
  static final int FRNAME = 0, LNAME = 1, AGE = 2, CLUB = 3, TIME = 4,
      tabMAX = 5;
  public ParseVar(String s) {
    s = s.toLowerCase();
    value = -1;
    type = VAR;
    if (s.equals("frname"))
      value = FRNAME;
    if (s.equals("lname"))
      value = LNAME;
    if (s.equals("age"))
      value = AGE;
    if (s.equals("club"))
      value = CLUB;
    if (s.equals("time"))
      value = TIME;
  }
  //--------------------------------------
  public boolean isLegal() {
    return (value >= 0);
  }
}
class Kid {
  String frname, lname, club;
  int age;
  float time;
  //-------------------------------------
  public Kid(String line) {
    StringTokenizer tok = new StringTokenizer(line);
    String lnum = tok.nextToken();
    frname = tok.nextToken();
    lname = tok.nextToken();
    age = new Integer(tok.nextToken()).intValue();
    club = tok.nextToken();
    time = new Float(tok.nextToken()).floatValue();
  }
  //-------------------------------
  public Object getData(int key) {
    switch (key) {
    case ParseVar.FRNAME:
      return frname;
    case ParseVar.LNAME:
      return lname;
    case ParseVar.CLUB:
      return club;
    case ParseVar.AGE:
      return new Integer(age);
    case ParseVar.TIME:
      return new Float(time);
    }
    return null;
  }
  //--------------------------------
  public int getAge() {
    return age;
  }
  public float getTime() {
    return time;
  }
  public String getFrname() {
    return frname;
  }
  public String getLname() {
    return lname;
  }
  public String getClub() {
    return club;
  }
}
class InputFile {
  RandomAccessFile f = null;
  boolean errflag;
  String s = null;
  public InputFile(String fname) {
    errflag = false;
    try {
      //open file
      f = new RandomAccessFile(fname, "r");
    } catch (IOException e) {
      //print error if not found
      System.out.println("no file found");
      errflag = true; //and set flag
    }
  }
  //-----------------------------------------
  public boolean checkErr() {
    return errflag;
  }
  //-----------------------------------------
  public String read() {
    //read a single field up to a comma or end of line
    String ret = "";
    if (s == null) //if no data in string
    {
      s = readLine(); //read next line
    }
    if (s != null) //if there is data
    {
      s.trim(); //trim off blanks
      int i = s.indexOf(","); //find next comma
      if (i <= 0) {
        ret = s.trim(); //if no commas go to end of line
        s = null; //and null out stored string
      } else {
        ret = s.substring(0, i).trim(); //return left of comma
        s = s.substring(i + 1); //save right of comma
      }
    } else
      ret = null;
    return ret; //return string
  }
  //-----------------------------------------
  public String readLine() {
    //read in a line from the file
    s = null;
    try {
      s = f.readLine(); //could throw error
    } catch (IOException e) {
      errflag = true;
      System.out.println("File read error");
    }
    return s;
  }
  //-----------------------------------------
  public void close() {
    try {
      f.close(); //close file
    } catch (IOException e) {
      System.out.println("File close error");
      errflag = true;
    }
  }
  //-----------------------------------------
}
class kidClub implements Enumeration {
  String clubMask; //name of club
  Kid kid; //next kid to return
  Enumeration ke; //gets all kids
  KidData kdata; //class containing kids
  //----------------------------------------
  public kidClub(KidData kd, String club) {
    clubMask = club; //save the club
    kdata = kd; //copy the class
    kid = null; //default
    ke = kdata.elements(); //get Enumerator
  }
  //----------------------------------------
  public boolean hasMoreElements() {
    //return true if there are any more kids
    //belonging to the specified club
    boolean found = false;
    while (ke.hasMoreElements() && !found) {
      kid = (Kid) ke.nextElement();
      found = kid.getClub().equals(clubMask);
    }
    if (!found)
      kid = null; //set to null if none left
    return found;
  }
  //----------------------------------------
  public Object nextElement() {
    if (kid != null)
      return kid;
    else
      //throw exception if access past end
      throw new NoSuchElementException();
  }
}
//50free.txt
/*
1 Amanda McCarthy             12  WCA         29.28
2 Jamie Falco                 12  HNHS        29.80
3 Meaghan O"Donnell           12  EDST        30.00
4 Greer Gibbs                 12  CDEV        30.04
5 Rhiannon Jeffrey            11  WYW         30.04
6 Sophie Connolly             12  WAC         30.05
7 Dana Helyer                 12  ARAC        30.18
8 Lindsay Marotto             12  OAK         30.23
9 Sarah Treichel              12  WYW         30.35
10 Ashley McEntee             12  RAC         30.47
11 Rachel Brookman            12  CAT         30.51
12 Michelle Ducharme          12  LEHY        30.51
13 Karleen Danais             12  NES         30.70
14 Megan Loock                12  WAC         30.90
15 Kaitlyn Ament              12  HNHS        30.93
16 Tara Schoen                12  WYW         31.01
17 Kate Olshefski             12  NCY         31.01
18 Emma Zuidema               12  HMST        31.07
19 Katie Persing              12  OAK         31.14
20 Christina Monsees          11  RAC         31.27
21 Kimberly Watcke            12  CDEV        31.50
22 Colleen Smith              12  AJSC        31.52
23 Chloe Osborne              12  GYWD        31.74
24 Natalia Fugate             12  WAC         31.75
25 Lisa McHale                11  RAC         31.76
26 Lindsay Cowles             11  NES         31.79
27 Jacquelyn Yavarone         12  HNHS        31.83
28 Molly Fenn                 12  WRAT        31.84
29 Karin Brudvig              12  HMST        31.84
30 Annie Duffy                12  MGAT        31.90
31 Nicole Coia                11  WCA         31.94
32 Elizabeth Rice             12  WYW         31.96
33 Yvette Landwehr            12  WRAT        32.00
34 Ashley Recklet             12  SHEL        32.24
35 Lauren McKenna             11  PSDY        32.27
36 Kristen Fontaine           12  EDST        32.28
37 Diana Cooke                12  ZEUS        32.33
38 Kimberly Gambino           11  NES         32.43
39 Jenny Morgan               11  NES         32.49
40 Colleen Coelho             12  CDEV        32.50
41 Leigh Gordon               12  CDEV        32.62
42 Caitlin Gillen             12  WYW         32.75
43 Kristen Skroski            12  HNHS        32.91
44 Sarah Greenberg            11  CDEV        32.97
45 Kathy Collins              12  EHBB        33.11
46 Morgan Bullock             12  ICSC        33.33
47 Brittany Medlin            12  CAT         33.33
48 Haley Ottenbreit           12  HNHS        33.35
49 Laura Kunces               11  WAC         33.64
50 Hayley Wolfgruber          12  WYW         33.73
51 Katie Duffy                12  MGAT        34.24

*/