Mega Code Archive

 
Categories / Java / Design Pattern
 

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