Bridge pattern in Java : Bridge Pattern « Design Pattern « Java






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


*/

           
       








Related examples in the same category

1.Bridge Pattern 1
2.Bridge Pattern in Java 3Bridge Pattern in Java 3