Java/Design Pattern/Proxy Pattern — различия между версиями

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

Текущая версия на 06:50, 1 июня 2010

Another Proxy Pattern

/*
Software Architecture Design Patterns in Java
by Partha Kuchana 
Auerbach Publications
*/

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
public class MainProxyApp {
  public static void main(String[] args) {
    OrderIF order = new OrderProxy();
    Vector v = order.getAllOrders();
    v = order.getAllOrders();
    v = order.getAllOrders();
    v = order.getAllOrders();
  }
}
class OrderProxy implements OrderIF {
  private int counter = 0;
  public Vector getAllOrders() {
    Order order = new Order();
    counter++;
    long t1 = System.currentTimeMillis();
    Vector v = order.getAllOrders();
    long t2 = System.currentTimeMillis();
    long timeDiff = t2 - t1;
    String msg = "Iteration=" + counter + "::Time=" + timeDiff + "ms";
    //log the message
    FileUtil fileUtil = new FileUtil();
    fileUtil.writeToFile("log.txt", msg, true, true);
    return v;
  }
}
interface OrderIF {
  public Vector getAllOrders();
}
class Order implements OrderIF {
  public Vector getAllOrders() {
    FileUtil fileUtil = new FileUtil();
    Vector v = fileUtil.fileToVector("orders.txt");
    return v;
  }
}
class MiscUtil {
  public static boolean hasDuplicates(Vector v) {
    int i = 0;
    int j = 0;
    boolean duplicates = false;
    for (i = 0; i < v.size() - 1; i++) {
      for (j = (i + 1); j < v.size(); j++) {
        if (v.elementAt(i).toString().equalsIgnoreCase(
            v.elementAt(j).toString())) {
          duplicates = true;
        }
      }
    }
    return duplicates;
  }
  public static Vector removeDuplicates(Vector s) {
    int i = 0;
    int j = 0;
    boolean duplicates = false;
    Vector v = new Vector();
    for (i = 0; i < s.size(); i++) {
      duplicates = false;
      for (j = (i + 1); j < s.size(); j++) {
        if (s.elementAt(i).toString().equalsIgnoreCase(
            s.elementAt(j).toString())) {
          duplicates = true;
        }
      }
      if (duplicates == false) {
        v.addElement(s.elementAt(i).toString().trim());
      }
    }
    return v;
  }
  public static Vector removeDuplicateDomains(Vector s) {
    int i = 0;
    int j = 0;
    boolean duplicates = false;
    String str1 = "";
    String str2 = "";
    Vector v = new Vector();
    for (i = 0; i < s.size(); i++) {
      duplicates = false;
      for (j = (i + 1); j < s.size(); j++) {
        str1 = "";
        str2 = "";
        str1 = s.elementAt(i).toString().trim();
        str2 = s.elementAt(j).toString().trim();
        if (str1.indexOf("@") > -1) {
          str1 = str1.substring(str1.indexOf("@"));
        }
        if (str2.indexOf("@") > -1) {
          str2 = str2.substring(str2.indexOf("@"));
        }
        if (str1.equalsIgnoreCase(str2)) {
          duplicates = true;
        }
      }
      if (duplicates == false) {
        v.addElement(s.elementAt(i).toString().trim());
      }
    }
    return v;
  }
  public static boolean areVectorsEqual(Vector a, Vector b) {
    if (a.size() != b.size()) {
      return false;
    }
    int i = 0;
    int vectorSize = a.size();
    boolean identical = true;
    for (i = 0; i < vectorSize; i++) {
      if (!(a.elementAt(i).toString().equalsIgnoreCase(b.elementAt(i)
          .toString()))) {
        identical = false;
      }
    }
    return identical;
  }
  public static Vector removeDuplicates(Vector a, Vector b) {
    int i = 0;
    int j = 0;
    boolean present = true;
    Vector v = new Vector();
    for (i = 0; i < a.size(); i++) {
      present = false;
      for (j = 0; j < b.size(); j++) {
        if (a.elementAt(i).toString().equalsIgnoreCase(
            b.elementAt(j).toString())) {
          present = true;
        }
      }
      if (!(present)) {
        v.addElement(a.elementAt(i));
      }
    }
    return v;
  }
}// end of class
class FileUtil {
  DataOutputStream dos;
  /*
   * Utility method to write a given text to a file
   */
  public boolean writeToFile(String fileName, String dataLine,
      boolean isAppendMode, boolean isNewLine) {
    if (isNewLine) {
      dataLine = "\n" + dataLine;
    }
    try {
      File outFile = new File(fileName);
      if (isAppendMode) {
        dos = new DataOutputStream(new FileOutputStream(fileName, true));
      } else {
        dos = new DataOutputStream(new FileOutputStream(outFile));
      }
      dos.writeBytes(dataLine);
      dos.close();
    } catch (FileNotFoundException ex) {
      return (false);
    } catch (IOException ex) {
      return (false);
    }
    return (true);
  }
  /*
   * Reads data from a given file
   */
  public String readFromFile(String fileName) {
    String DataLine = "";
    try {
      File inFile = new File(fileName);
      BufferedReader br = new BufferedReader(new InputStreamReader(
          new FileInputStream(inFile)));
      DataLine = br.readLine();
      br.close();
    } catch (FileNotFoundException ex) {
      return (null);
    } catch (IOException ex) {
      return (null);
    }
    return (DataLine);
  }
  public boolean isFileExists(String fileName) {
    File file = new File(fileName);
    return file.exists();
  }
  public boolean deleteFile(String fileName) {
    File file = new File(fileName);
    return file.delete();
  }
  /*
   * Reads data from a given file into a Vector
   */
  public Vector fileToVector(String fileName) {
    Vector v = new Vector();
    String inputLine;
    try {
      File inFile = new File(fileName);
      BufferedReader br = new BufferedReader(new InputStreamReader(
          new FileInputStream(inFile)));
      while ((inputLine = br.readLine()) != null) {
        v.addElement(inputLine.trim());
      }
      br.close();
    } // Try
    catch (FileNotFoundException ex) {
      //
    } catch (IOException ex) {
      //
    }
    return (v);
  }
  /*
   * Writes data from an input vector to a given file
   */
  public void vectorToFile(Vector v, String fileName) {
    for (int i = 0; i < v.size(); i++) {
      writeToFile(fileName, (String) v.elementAt(i), true, true);
    }
  }
  /*
   * Copies unique rows from a source file to a destination file
   */
  public void copyUniqueElements(String sourceFile, String resultFile) {
    Vector v = fileToVector(sourceFile);
    v = MiscUtil.removeDuplicates(v);
    vectorToFile(v, resultFile);
  }
} // end FileUtil





Proxy Pattern 2

//[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.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
public class RunProxyPattern {
  public static void main(String[] arguments) {
    System.out.println("Example for the Proxy pattern");
    System.out.println();
    System.out.println("This code will demonstrate the use of a Proxy to");
    System.out.println(" provide functionality in place of its underlying");
    System.out.println(" class.");
    System.out.println();
    System.out
        .println(" Initially, an AddressBookProxy object will provide");
    System.out.println(" address book support without requiring that the");
    System.out
        .println(" AddressBookImpl be created. This could potentially");
    System.out.println(" make the application run much faster, since the");
    System.out
        .println(" AddressBookImpl would need to read in all addresses");
    System.out.println(" from a file when it is first created.");
    System.out.println();
    if (!(new File("data.ser").exists())) {
      DataCreator.serialize("data.ser");
    }
    System.out.println("Creating the AddressBookProxy");
    AddressBookProxy proxy = new AddressBookProxy("data.ser");
    System.out.println("Adding entries to the AddressBookProxy");
    System.out.println("(this operation can be done by the Proxy, without");
    System.out.println(" creating an AddressBookImpl object)");
    proxy.add(new AddressImpl("Sun Education [CO]", "500 El Dorado Blvd.",
        "Broomfield", "CO", "80020"));
    proxy.add(new AddressImpl("Apple Inc.", "1 Infinite Loop",
        "Redwood City", "CA", "93741"));
    System.out.println("Addresses created. Retrieving an address");
    System.out
        .println("(since the address is stored by the Proxy, there is");
    System.out
        .println(" still no need to create an AddressBookImpl object)");
    System.out.println();
    System.out.println(proxy.getAddress("Sun Education [CO]").getAddress());
    System.out.println();
    System.out
        .println("So far, all operations have been handled by the Proxy,");
    System.out
        .println(" without any involvement from the AddressBookImpl.");
    System.out.println(" Now, a call to the method getAllAddresses will");
    System.out.println(" force instantiation of AddressBookImpl, and will");
    System.out.println(" retrieve ALL addresses that are stored.");
    System.out.println();
    ArrayList addresses = proxy.getAllAddresses();
    System.out.println("Addresses retrieved. Addresses currently stored:");
    System.out.println(addresses);
  }
}
interface Address extends Serializable {
  public static final String EOL_STRING = System
      .getProperty("line.separator");
  public static final String SPACE = " ";
  public static final String COMMA = ",";
  public String getAddress();
  public String getType();
  public String getDescription();
  public String getStreet();
  public String getCity();
  public String getState();
  public String getZipCode();
  public void setType(String newType);
  public void setDescription(String newDescription);
  public void setStreet(String newStreet);
  public void setCity(String newCity);
  public void setState(String newState);
  public void setZipCode(String newZip);
}
interface AddressBook {
  public void add(Address address);
  public ArrayList getAllAddresses();
  public Address getAddress(String description);
  public void open();
  public void save();
}
class FileLoader {
  public static Object loadData(File inputFile) {
    Object returnValue = null;
    try {
      if (inputFile.exists()) {
        if (inputFile.isFile()) {
          ObjectInputStream readIn = new ObjectInputStream(
              new FileInputStream(inputFile));
          returnValue = readIn.readObject();
          readIn.close();
        } else {
          System.err.println(inputFile + " is a directory.");
        }
      } else {
        System.err.println("File " + inputFile + " does not exist.");
      }
    } catch (ClassNotFoundException exc) {
      exc.printStackTrace();
    } catch (IOException exc) {
      exc.printStackTrace();
    }
    return returnValue;
  }
  public static void storeData(File outputFile, Serializable data) {
    try {
      ObjectOutputStream writeOut = new ObjectOutputStream(
          new FileOutputStream(outputFile));
      writeOut.writeObject(data);
      writeOut.close();
    } catch (IOException exc) {
      exc.printStackTrace();
    }
  }
}
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() {
    ArrayList items = new ArrayList();
    items.add(new AddressImpl("Home address", "1418 Appian Way",
        "Pleasantville", "NH", "27415"));
    items.add(new AddressImpl("Resort", "711 Casino Ave.", "Atlantic City",
        "NJ", "91720"));
    items.add(new AddressImpl("Vacation spot", "90 Ka"ahanau Cir.",
        "Haleiwa", "HI", "41720"));
    return items;
  }
  private static void serializeToFile(Serializable data, String fileName)
      throws IOException {
    ObjectOutputStream serOut = new ObjectOutputStream(
        new FileOutputStream(fileName));
    serOut.writeObject(data);
    serOut.close();
  }
}
class AddressImpl implements Address {
  private String type;
  private String description;
  private String street;
  private String city;
  private String state;
  private String zipCode;
  public static final String HOME = "home";
  public static final String WORK = "work";
  public AddressImpl() {
  }
  public AddressImpl(String newDescription, String newStreet, String newCity,
      String newState, String newZipCode) {
    description = newDescription;
    street = newStreet;
    city = newCity;
    state = newState;
    zipCode = newZipCode;
  }
  public String getType() {
    return type;
  }
  public String getDescription() {
    return description;
  }
  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 setDescription(String newDescription) {
    description = newDescription;
  }
  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 String toString() {
    return description;
  }
  public String getAddress() {
    return description + EOL_STRING + street + EOL_STRING + city + COMMA
        + SPACE + state + SPACE + zipCode + EOL_STRING;
  }
}
class AddressBookProxy implements AddressBook {
  private File file;
  private AddressBookImpl addressBook;
  private ArrayList localAddresses = new ArrayList();
  public AddressBookProxy(String filename) {
    file = new File(filename);
  }
  public void open() {
    addressBook = new AddressBookImpl(file);
    Iterator addressIterator = localAddresses.iterator();
    while (addressIterator.hasNext()) {
      addressBook.add((Address) addressIterator.next());
    }
  }
  public void save() {
    if (addressBook != null) {
      addressBook.save();
    } else if (!localAddresses.isEmpty()) {
      open();
      addressBook.save();
    }
  }
  public ArrayList getAllAddresses() {
    if (addressBook == null) {
      open();
    }
    return addressBook.getAllAddresses();
  }
  public Address getAddress(String description) {
    if (!localAddresses.isEmpty()) {
      Iterator addressIterator = localAddresses.iterator();
      while (addressIterator.hasNext()) {
        AddressImpl address = (AddressImpl) addressIterator.next();
        if (address.getDescription().equalsIgnoreCase(description)) {
          return address;
        }
      }
    }
    if (addressBook == null) {
      open();
    }
    return addressBook.getAddress(description);
  }
  public void add(Address address) {
    if (addressBook != null) {
      addressBook.add(address);
    } else if (!localAddresses.contains(address)) {
      localAddresses.add(address);
    }
  }
}
class AddressBookImpl implements AddressBook {
  private File file;
  private ArrayList addresses = new ArrayList();
  public AddressBookImpl(File newFile) {
    file = newFile;
    open();
  }
  public ArrayList getAllAddresses() {
    return addresses;
  }
  public Address getAddress(String description) {
    Iterator addressIterator = addresses.iterator();
    while (addressIterator.hasNext()) {
      AddressImpl address = (AddressImpl) addressIterator.next();
      if (address.getDescription().equalsIgnoreCase(description)) {
        return address;
      }
    }
    return null;
  }
  public void add(Address address) {
    if (!addresses.contains(address)) {
      addresses.add(address);
    }
  }
  public void open() {
    addresses = (ArrayList) FileLoader.loadData(file);
  }
  public void save() {
    FileLoader.storeData(file, addresses);
  }
}





Proxy 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.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Label;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ProxyDisplay extends JFrame {
  public ProxyDisplay() {
    super("Display proxied image");
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    JPanel p = new JPanel();
    getContentPane().add(p);
    p.setLayout(new BorderLayout());
    ImageProxy image = new ImageProxy("elliott.jpg", 321, 271);
    p.add("Center", image);
    p.add("North", new Label("    "));
    p.add("West", new Label("  "));
    setSize(370, 350);
    setVisible(true);
  }
  
  static public void main(String[] argv) {
    new ProxyDisplay();
  }
}
//==================================
class ImageProxy extends JPanel implements Runnable {
  int height, width;
  MediaTracker tracker;
  Image img;
  JFrame frame;
  Thread imageCheck; //to monitor loading
  
  public ImageProxy(String filename, int w, int h) {
    height = h;
    width = w;
    tracker = new MediaTracker(this);
    img = Toolkit.getDefaultToolkit().getImage(filename);
    tracker.addImage(img, 0); //watch for image loading
    imageCheck = new Thread(this);
    imageCheck.start(); //start 2nd thread monitor
    //this begins actual image loading
    try {
      tracker.waitForID(0, 1);
    } catch (InterruptedException e) {
    }
  }
  
  public void paint(Graphics g) {
    if (tracker.checkID(0)) {
      height = img.getHeight(frame); //get height
      width = img.getWidth(frame); //and width
      g.setColor(Color.lightGray); //erase box
      g.fillRect(0, 0, width, height);
      g.drawImage(img, 0, 0, this); //draw loaded image
    } else {
      //draw box outlining image if not loaded yet
      g.setColor(Color.black);
      g.drawRect(1, 1, width - 2, height - 2);
    }
  }
  
  public Dimension getPreferredSize() {
    return new Dimension(width, height);
  }
  //public int getWidth() {return width;}
  //public int getHeight(){return height;}
  
  public void run() {
    //this thread monitors image loading
    //and repaints when done
    //the 1000 msec is artifically long
    //to allow demo to display with delay
    try {
      Thread.sleep(1000);
      while (!tracker.checkID(0))
        Thread.sleep(1000);
    } catch (Exception e) {
    }
    repaint();
  }
}