Java/Design Pattern/Bridge Pattern

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

Bridge Pattern 1

/*
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 BridgePatternClient {
  public static void main(String[] args) {
    //Create an appropriate implementer object
    MessageLogger logger = new FileLogger();
    //Choose required interface object and
    // configure it with the implementer object
    Message msg = new EncryptedMessage(logger);
    msg.log("Test Message");
  }
}
class ConsoleLogger implements MessageLogger {
  public void logMsg(String msg) {
    System.out.println(msg);
  }
}
class EncryptedMessage implements Message {
  private MessageLogger logger;
  public EncryptedMessage(MessageLogger l) {
    logger = l;
  }
  public void log(String msg) {
    String str = preProcess(msg);
    logger.logMsg(str);
  }
  private String preProcess(String msg) {
    msg = msg.substring(msg.length() - 1)
        + msg.substring(0, msg.length() - 1);
    return msg;
  };
}
class FileLogger implements MessageLogger {
  public void logMsg(String msg) {
    FileUtil futil = new FileUtil();
    futil.writeToFile("log.txt", msg, true, true);
  }
}
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
interface Message {
  public void log(String msg);
}
interface MessageLogger {
  public void logMsg(String msg);
}
class TextMessage implements Message {
  private MessageLogger logger;
  public TextMessage(MessageLogger l) {
    logger = l;
  }
  public void log(String msg) {
    String str = preProcess(msg);
    logger.logMsg(str);
  }
  private String preProcess(String msg) {
    return msg;
  };
}





Bridge 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.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Vector;
import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
public class productDisplay extends JFrame {
  public productDisplay() {
    super("The Java Factory-- Products");
    setLF(); //set look and feel
    setCloseClick(); //set close on window close click
    InputFile f = new InputFile("products.txt");
    Vector prod = new Vector();
    //read in product list
    String s = f.readLine();
    while (s != null) {
      prod.addElement(s);
      s = f.readLine();
    }
    JPanel p = new JPanel();
    getContentPane().add(p);
    p.setLayout(new GridLayout(1, 2));
    JPanel pleft = new JPanel();
    JPanel pright = new JPanel();
    p.add(pleft);
    p.add(pright);
    pleft.setLayout(new BorderLayout());
    pright.setLayout(new BorderLayout());
    //add in customer view as list box
    pleft.add("North", new JLabel("Customer view"));
    pleft.add("Center", new productList(prod));
    //add in execute view as table
    pright.add("North", new JLabel("Executive view"));
    pright.add("Center", new productTable(prod));
    setSize(new Dimension(400, 300));
    setVisible(true);
  }
  //-----------------------------------------
  private void setCloseClick() {
    //create window listener to respond to window close click
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
  //------------------------------------------
  private void setLF() {
    // Force SwingApp to come up in the System L&F
    String laf = UIManager.getSystemLookAndFeelClassName();
    try {
      UIManager.setLookAndFeel(laf);
    } catch (UnsupportedLookAndFeelException exc) {
      System.err.println("Warning: UnsupportedLookAndFeel: " + laf);
    } catch (Exception exc) {
      System.err.println("Error loading " + laf + ": " + exc);
    }
  }
  //---------------------------------------------
  static public void main(String argv[]) {
    new productDisplay();
  }
}
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 productList extends JawtList {
  public productList(Vector products) {
    super(products.size()); //for compatibility
    for (int i = 0; i < products.size(); i++) {
      //take each strig apart and keep only
      //the product names, discarding the quntities
      String s = (String) products.elementAt(i);
      int index = s.indexOf("--"); //separate qty from name
      if (index > 0)
        add(s.substring(0, index));
      else
        add(s);
    }
  }
}
class productTable extends JScrollPane {
  JTable table;
  public productTable(Vector list) {
    table = new JTable(new prodModel(list));
    getViewport().add(table);
  }
}
class prodModel implements TableModel {
  int rows, columns;
  Vector prodNames, quantities;
  public prodModel(Vector products) {
    rows = products.size();
    columns = 2;
    prodNames = new Vector();
    quantities = new Vector();
    for (int i = 0; i < products.size(); i++) {
      String s = (String) products.elementAt(i);
      int index = s.indexOf("--"); //separate qty from name
      if (index > 0) {
        prodNames.addElement(s.substring(0, index));
        quantities.addElement(s.substring(index + 2).trim());
      } else
        prodNames.addElement(s);
    }
  }
  public int getColumnCount() {
    return columns;
  }
  public int getRowCount() {
    return rows;
  }
  public Object getValueAt(int r, int c) {
    switch (c) {
    case 0:
      return prodNames.elementAt(r);
    case 1:
      return quantities.elementAt(r);
    default:
      return prodNames.elementAt(r);
    }
  }
  public Class getColumnClass(int c) {
    return (new String("")).getClass();
  }
  public boolean isCellEditable(int r, int c) {
    return false;
  }
  public String getColumnName(int c) {
    return "";
  }
  public void setValueAt(Object obj, int r, int c) {
  }
  public void addTableModelListener(TableModelListener tbm) {
  }
  public void removeTableModelListener(TableModelListener tbm) {
  }
}
//this is a simple adapter class to
//convert List awt methods to Swing methods
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 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());
  }
}
interface awtList {
  public void add(String s);
  public void remove(String s);
  public String[] getSelectedItems();
}
//products.txt
/*
Brass plated widgets --1,000,076
Furled frammis       --75,000
Detailed rat brushes --700
Zero-based hex dumps--80,000
Anterior antelope collars --578
Washable softwear --789,000
Steel-toed wing-tips --456,666

*/





Bridge Pattern in Java 3

//[C] 2002 Sun Microsystems, Inc.---
import java.util.ArrayList;
public class RunBridgePattern {
    public static void main(String [] arguments){
        System.out.println("Example for the Bridge pattern");
        System.out.println();
        System.out.println("This example divides complex behavior among two");
        System.out.println(" classes - the abstraction and the implementation.");
        System.out.println();
        System.out.println("In this case, there are two classes which can provide the");
        System.out.println(" abstraction - BaseList and OrnamentedList. The BaseList");
        System.out.println(" provides core funtionality, while the OrnamentedList");
        System.out.println(" expands on the model by adding a list character.");
        System.out.println();
        System.out.println("The OrderedListImpl class provides the underlying storage");
        System.out.println(" capability for the list, and can be flexibly paired with");
        System.out.println(" either of the classes which provide the abstraction.");
        
        System.out.println("Creating the OrderedListImpl object.");
        ListImpl implementation = new OrderedListImpl();
        
        System.out.println("Creating the BaseList object.");
        BaseList listOne = new BaseList();
        listOne.setImplementor(implementation);
        System.out.println();
        
        System.out.println("Adding elements to the list.");
        listOne.add("One");
        listOne.add("Two");
        listOne.add("Three");
        listOne.add("Four");
        System.out.println();
        
        System.out.println("Creating an OrnamentedList object.");
        OrnamentedList listTwo = new OrnamentedList();
        listTwo.setImplementor(implementation);
        listTwo.setItemType("+");
        System.out.println();
        
        System.out.println("Creating an NumberedList object.");
        NumberedList listThree = new NumberedList();
        listThree.setImplementor(implementation);
        System.out.println();
        
        System.out.println("Printing out first list (BaseList)");
        for (int i = 0; i < listOne.count(); i++){
            System.out.println("\t" + listOne.get(i));
        }
        System.out.println();
        
        System.out.println("Printing out second list (OrnamentedList)");
        for (int i = 0; i < listTwo.count(); i++){
            System.out.println("\t" + listTwo.get(i));
        }
        System.out.println();
        
        System.out.println("Printing our third list (NumberedList)");
        for (int i = 0; i < listThree.count(); i++){
            System.out.println("\t" + listThree.get(i));
        }
    }
}
interface ListImpl{
    public void addItem(String item);
    public void addItem(String item, int position);
    public void removeItem(String item);
    public int getNumberOfItems();
    public String getItem(int index);
    public boolean supportsOrdering();
}
class BaseList{
    protected ListImpl implementor;
    
    public void setImplementor(ListImpl impl){
        implementor = impl;
    }
    
    public void add(String item){
        implementor.addItem(item);
    }
    public void add(String item, int position){
        if (implementor.supportsOrdering()){
            implementor.addItem(item, position);
        }
    }
    
    public void remove(String item){
        implementor.removeItem(item);
    }
    
    public String get(int index){
        return implementor.getItem(index);
    }
    
    public int count(){
        return implementor.getNumberOfItems();
    }
}
class NumberedList extends BaseList{
    public String get(int index){
        return (index + 1) + ". " + super.get(index);
    }
}
class OrderedListImpl implements ListImpl{
    private ArrayList items = new ArrayList();
    
    public void addItem(String item){
        if (!items.contains(item)){
            items.add(item);
        }
    }
    public void addItem(String item, int position){
        if (!items.contains(item)){
            items.add(position, item);
        }
    }
    
    public void removeItem(String item){
        if (items.contains(item)){
            items.remove(items.indexOf(item));
        }
    }
    
    public boolean supportsOrdering(){
        return true;
    }
    
    public int getNumberOfItems(){
        return items.size();
    }
    
    public String getItem(int index){
        if (index < items.size()){
            return (String)items.get(index);
        }
        return null;
    }
}
class OrnamentedList extends BaseList{
    private char itemType;
    
    public char getItemType(){ return itemType; }
    public void setItemType(char newItemType){
        if (newItemType > " "){
            itemType = newItemType;
        }
    }
    
    public String get(int index){
        return itemType + " " + super.get(index);
    }
}