Java/Design Pattern/Prototype Pattern

Материал из Java эксперт
Перейти к: навигация, поиск

Prototype pattern in Java

/*
The Design Patterns Java Companion
Copyright (C) 1998, by James W. Cooper
IBM Thomas J. Watson Research Center
*/
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.util.StringTokenizer;
import java.util.Vector;
public class SwimInfo extends Frame implements ActionListener {
  SwimData sdata, sxdata = null;
  List swList, cloneList;
  Button Clone, Refresh, Quit;
  Swimmer sw;
  public SwimInfo() {
    super("Prototype example");
    sdata = new SwimData("swimmers.txt");
    setGUI();
    loadswList();
  }
  //-
  public void actionPerformed(ActionEvent e) {
    Object obj = e.getSource();
    if (obj == Clone)
      cloneAndLoad();
    if (obj == Refresh)
      loadswList();
    if (obj == Quit)
      System.exit(0);
  }
  //-
  private void cloneAndLoad() {
    //sxdata = (SwimData)sdata.deepClone();
    sxdata = (SwimData) sdata.clone();
    sxdata.sortByTime();
    cloneList.removeAll();
    //now print out sorted values from clone
    for (int i = 0; i < sxdata.size(); i++) {
      sw = sxdata.getSwimmer(i);
      cloneList.addItem(sw.getName() + " " + sw.getTime());
    }
  }
  //-
  private void loadswList() {
    swList.removeAll();
    for (int i = 0; i < sdata.size(); i++) {
      sw = sdata.getSwimmer(i);
      swList.addItem(sw.getName() + " " + sw.getTime());
    }
  }
  //-
  private void setGUI() {
    setLayout(new GridLayout(1, 3));
    setBackground(Color.lightGray);
    swList = new List(15);
    cloneList = new List(15);
    Panel cp = new Panel();
    add(swList);
    add(cp);
    add(cloneList);
    Clone = new Button("Clone >");
    Refresh = new Button("<Refresh");
    Quit = new Button("Quit");
    cp.setLayout(new GridLayout(3, 1));
    Panel p1 = new Panel();
    cp.add(p1);
    p1.add(Clone);
    Panel p2 = new Panel();
    cp.add(p2);
    p2.add(Refresh);
    Panel p3 = new Panel();
    cp.add(p3);
    p3.add(Quit);
    Clone.addActionListener(this);
    Refresh.addActionListener(this);
    Quit.addActionListener(this);
    setBounds(100, 100, 500, 400);
    setVisible(true);
  }
  //-
  static public void main(String argv[]) {
    new SwimInfo();
  }
}
class SwimmerNoSex extends SwimData {
  public SwimmerNoSex(String fileName) {
      super(fileName);
  }
  public void sortByTime() {
  }
}
class SwimData implements Cloneable, Serializable {
  protected Vector swimmers;
  public SwimData(String filename) {
    String s = "";
    swimmers = new Vector();
    InputFile f = new InputFile(filename);
    s = f.readLine();
    while (s != null) {
      swimmers.addElement(new Swimmer(s));
      s = f.readLine();
    }
    f.close();
  }
  
  public int size() {
    return swimmers.size();
  }
  
  public Swimmer getSwimmer(int i) {
    if ((i >= 0) && (i < swimmers.size()))
      return (Swimmer) swimmers.elementAt(i);
    else
      return null;
  }
  
  public void sortByTime() {
    Swimmer sw;
    int i, j;
    int max = swimmers.size();
    Swimmer sd[] = new Swimmer[max];
    for (i = 0; i < max; i++)
      sd[i] = (Swimmer) swimmers.elementAt(i);
    for (i = 0; i < max; i++) {
      for (j = i; j < max; j++) {
        if (sd[i].getTime() > sd[j].getTime()) {
          sw = sd[i];
          sd[i] = sd[j];
          sd[j] = sw;
        }
      }
    }
    // swimmers = new Vector();
    swimmers.removeAllElements();
    for (i = 0; i < max; i++)
      swimmers.addElement(sd[i]);
  }
  
  public Object deepClone() {
    try {
      ByteArrayOutputStream b = new ByteArrayOutputStream();
      ObjectOutputStream out = new ObjectOutputStream(b);
      out.writeObject(this);
      ByteArrayInputStream bIn = new ByteArrayInputStream(b.toByteArray());
      ObjectInputStream oi = new ObjectInputStream(bIn);
      return (oi.readObject());
    } catch (Exception e) {
      System.out.println("exception:" + e.getMessage());
      e.printStackTrace();
      return null;
    }
  }
  
  public Object clone() {
    try {
      return super.clone();
    } catch (Exception e) {
      System.out.println(e.getMessage());
      return null;
    }
  }
}
//==============================================
class Swimmer implements Serializable {
  String name;
  int age;
  String club;
  float time;
  boolean female;
  public Swimmer(String dataline) {
    StringTokenizer st = new StringTokenizer(dataline, ",");
    name = st.nextToken();
    age = new Integer(st.nextToken().trim()).intValue();
    club = st.nextToken().trim();
    time = new Float(st.nextToken().trim()).floatValue();
    //System.out.println(name+" "+time);
    String sx = st.nextToken().trim().toUpperCase();
    female = sx.equals("F");
  }
  public boolean isFemale() {
    return female;
  }
  public int getAge() {
    return age;
  }
  public float getTime() {
    return time;
  }
  public String getName() {
    return name;
  }
  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;
    }
  }
  
}
//Swimmers.txt
/*
Kristen Frost, 9, CAT, 26.31, F
Kimberly Watcke, 10, CDEV,27.37, F
Jaclyn Carey, 10, ARAC, 27.53, F
Megan Crapster, 10, LEHY, 27.68, F
Kaitlyn Ament, 10, HNHS, 28.20, F
Jackie Rogers, 10, WCA, 28.68, F
Erin McLaughlin, 9, HMST, 28.80, F
Emily Ferrier, 10, NMIL, 28.85, F
Aurora Lee, 8, FFLY, 28.88, F
Kate Isselee, 9, NMIL, 28.91, F
Luke Mester, 10, GYWD, 24.88,  M
Stephen Cosme, 9, OAK, 27.89, M
Jeffrey Sudbury, 10, WYW, 28.24, M
Ernest Verrico, 9, SHKS, 28.46, M
David Liebovitz, 10, WYW, 28.78, M
Ryan Rynazewski, 10, AJSC, 28.83, M
Matthew Donch, 9, PSDY, 28.95, M
Christopher Prus, 10, RAYS, 29.02, M
Charles Baker, 10, PSDY, 29.06, M
Matthew Sweitzer, 10, SHKS, 29.10, M
*/





Prototype Pattern in Java 2

//[C] 2002 Sun Microsystems, Inc.---

public class RunPrototypePattern {
  public static void main(String[] arguments) {
    System.out.println("Example for Prototype pattern");
    System.out.println();
    System.out.println("This example will create an Address object,");
    System.out.println(" which it will then duplicate by calling the");
    System.out.println(" object"s clone method.");
    System.out.println();
    System.out.println("Creating first address.");
    Address address1 = new Address("8445 Silverado Trail", "Rutherford",
        "CA", "91734");
    System.out.println("First address created.");
    System.out.println("    Hash code = " + address1.hashCode());
    System.out.println(address1);
    System.out.println();
    System.out.println("Creating second address using the clone() method.");
    Address address2 = (Address) address1.copy();
    System.out.println("Second address created.");
    System.out.println("    Hash code = " + address2.hashCode());
    System.out.println(address2);
    System.out.println();
  }
}
interface Copyable {
  public Object copy();
}
class Address implements Copyable {
  private String type;
  private String street;
  private String city;
  private String state;
  private String zipCode;
  public static final String EOL_STRING = System
      .getProperty("line.separator");
  public static final String COMMA = ",";
  public static final String HOME = "home";
  public static final String WORK = "work";
  public Address(String initType, String initStreet, String initCity,
      String initState, String initZip) {
    type = initType;
    street = initStreet;
    city = initCity;
    state = initState;
    zipCode = initZip;
  }
  public Address(String initStreet, String initCity, String initState,
      String initZip) {
    this(WORK, initStreet, initCity, initState, initZip);
  }
  public Address(String initType) {
    type = initType;
  }
  public Address() {
  }
  public String getType() {
    return type;
  }
  public String getStreet() {
    return street;
  }
  public String getCity() {
    return city;
  }
  public String getState() {
    return state;
  }
  public String getZipCode() {
    return zipCode;
  }
  public void setType(String newType) {
    type = newType;
  }
  public void setStreet(String newStreet) {
    street = newStreet;
  }
  public void setCity(String newCity) {
    city = newCity;
  }
  public void setState(String newState) {
    state = newState;
  }
  public void setZipCode(String newZip) {
    zipCode = newZip;
  }
  public Object copy() {
    return new Address(street, city, state, zipCode);
  }
  public String toString() {
    return "\t" + street + COMMA + " " + EOL_STRING + "\t" + city + COMMA
        + " " + state + " " + zipCode;
  }
}