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

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

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

Facade Pattern

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





Facade Pattern 2 in Java

//[C] 2002 Sun Microsystems, Inc.---
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Properties;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class RunFacadePattern {
    public static void main(String [] arguments){
        System.out.println("Example for the Facade pattern");
        System.out.println();
        System.out.println("This code sample uses an InternationalizatgionWizard (a Facade)");
        System.out.println(" to manage communication between the rest of the application and");
        System.out.println(" a series of other classes.");
        System.out.println();
        System.out.println("The InternationalizatgionWizard maintains a colleciton of Nation");
        System.out.println(" objects. When the setNation method is called, the wizard sets the");
        System.out.println(" default nation, updating the Currency, PhoneNumber and localized");
        System.out.println(" String resources (InternationalizedText) available.");
        System.out.println();
        System.out.println("Calls to get Strings for the GUI, the currency symbol or the dialing");
        System.out.println(" prefix are routed through the Facade, the InternationalizationWizard.");
        System.out.println();
        
        if (!(new File("data.ser").exists())){
            DataCreator.serialize("data.ser");
        }
        
        System.out.println("Creating the InternationalizationWizard and setting the nation to US.");
        System.out.println();
        InternationalizationWizard wizard = new InternationalizationWizard();
        wizard.setNation("US");
        
        System.out.println("Creating the FacadeGui.");
        System.out.println();
        FacadeGui application = new FacadeGui(wizard);
        application.createGui();
        application.setNation(wizard.getNation("US"));
    }
}
class FacadeGui implements ActionListener, ItemListener{
    private static final String GUI_TITLE = "title";
    private static final String EXIT_CAPTION = "exit";
    private static final String COUNTRY_LABEL = "country";
    private static final String CURRENCY_LABEL = "currency";
    private static final String PHONE_LABEL = "phone";
    
    private JFrame mainFrame;
    private JButton exit;
    private JComboBox countryChooser;
    private JPanel controlPanel, displayPanel;
    private JLabel countryLabel, currencyLabel, phoneLabel;
    private JTextField currencyTextField, phoneTextField;
    private InternationalizationWizard nationalityFacade;
    
    public FacadeGui(InternationalizationWizard wizard){
        nationalityFacade = wizard;
    }
    
    public void createGui(){
        mainFrame = new JFrame(nationalityFacade.getProperty(GUI_TITLE));
        Container content = mainFrame.getContentPane();
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
        
        displayPanel = new JPanel();
        displayPanel.setLayout(new GridLayout(3, 2));
        
        countryLabel = new JLabel(nationalityFacade.getProperty(COUNTRY_LABEL));
        countryChooser = new JComboBox(nationalityFacade.getNations());
        currencyLabel = new JLabel(nationalityFacade.getProperty(CURRENCY_LABEL));
        currencyTextField = new JTextField();
        phoneLabel = new JLabel(nationalityFacade.getProperty(PHONE_LABEL));
        phoneTextField = new JTextField();
        
        currencyTextField.setEditable(false);
        phoneTextField.setEditable(false);
        
        displayPanel.add(countryLabel);
        displayPanel.add(countryChooser);
        displayPanel.add(currencyLabel);
        displayPanel.add(currencyTextField);
        displayPanel.add(phoneLabel);
        displayPanel.add(phoneTextField);
        content.add(displayPanel);
        
        controlPanel = new JPanel();
        exit = new JButton(nationalityFacade.getProperty(EXIT_CAPTION));
        controlPanel.add(exit);
        content.add(controlPanel);
        
        exit.addActionListener(this);
        countryChooser.addItemListener(this);
        
        mainFrame.addWindowListener(new WindowCloseManager());
        mainFrame.pack();
        mainFrame.setVisible(true);
    }
    
    private void updateGui(){
        nationalityFacade.setNation(countryChooser.getSelectedItem().toString());
        mainFrame.setTitle(nationalityFacade.getProperty(GUI_TITLE));
        countryLabel.setText(nationalityFacade.getProperty(COUNTRY_LABEL));
        currencyLabel.setText(nationalityFacade.getProperty(CURRENCY_LABEL));
        phoneLabel.setText(nationalityFacade.getProperty(PHONE_LABEL));
        exit.setText(nationalityFacade.getProperty(EXIT_CAPTION));
        currencyTextField.setText(nationalityFacade.getCurrencySymbol() + " " +
            nationalityFacade.getNumberFormat().format(5280.50));
        phoneTextField.setText(nationalityFacade.getPhonePrefix());
        mainFrame.invalidate();
        countryLabel.invalidate();
        currencyLabel.invalidate();
        phoneLabel.invalidate();
        exit.invalidate();
        mainFrame.validate();
    }
    
    public void actionPerformed(ActionEvent evt){
        Object originator = evt.getSource();
        if (originator == exit){
            exitApplication();
        }
    }
    public void itemStateChanged(ItemEvent evt){
        Object originator = evt.getSource();
        if (originator == countryChooser){
            updateGui();
        }
    }
    
    public void setNation(Nation nation){
        countryChooser.setSelectedItem(nation);
    }
    
    private class WindowCloseManager extends WindowAdapter{
        public void windowClosing(WindowEvent evt){
            exitApplication();
        }
    }
    
    private void exitApplication(){
        System.exit(0);
    }
}
class Nation {
    private char symbol;
    private String name;
    private String dialingPrefix;
    private String propertyFileName;
    private NumberFormat numberFormat;
    
    public Nation(String newName, char newSymbol, String newDialingPrefix,
        String newPropertyFileName, NumberFormat newNumberFormat) {
        name = newName;
        symbol = newSymbol;
        dialingPrefix = newDialingPrefix;
        propertyFileName = newPropertyFileName;
        numberFormat = newNumberFormat;
    }
    
    public String getName(){ return name; }
    public char getSymbol(){ return symbol; }
    public String getDialingPrefix(){ return dialingPrefix; }
    public String getPropertyFileName(){ return propertyFileName; }
    public NumberFormat getNumberFormat(){ return numberFormat; }
    
    public String toString(){ return name; }
}
class Currency{
    private char currencySymbol;
    private NumberFormat numberFormat;
    
    public void setCurrencySymbol(char newCurrencySymbol){ currencySymbol = newCurrencySymbol; }
    public void setNumberFormat(NumberFormat newNumberFormat){ numberFormat = newNumberFormat; }
    
    public char getCurrencySymbol(){ return currencySymbol; }
    public NumberFormat getNumberFormat(){ return numberFormat; }
}
class DataCreator{
    private static final String GUI_TITLE = "title";
    private static final String EXIT_CAPTION = "exit";
    private static final String COUNTRY_LABEL = "country";
    private static final String CURRENCY_LABEL = "currency";
    private static final String PHONE_LABEL = "phone";
    
    public static void serialize(String fileName){
        saveFrData();
        saveUsData();
        saveNlData();
    }
    
    private static void saveFrData(){
        try{
            Properties textSettings = new Properties();
            textSettings.setProperty(GUI_TITLE, "Demonstration du Pattern Facade");
            textSettings.setProperty(EXIT_CAPTION, "Sortir");
            textSettings.setProperty(COUNTRY_LABEL, "Pays");
            textSettings.setProperty(CURRENCY_LABEL, "Monnaie");
            textSettings.setProperty(PHONE_LABEL, "Numero de Telephone");
            textSettings.store(new FileOutputStream("french.properties"), "French Settings");
        }
        catch (IOException exc){
            System.err.println("Error storing settings to output");
            exc.printStackTrace();
        }
    }
    private static void saveUsData(){
        try{
            Properties textSettings = new Properties();
            textSettings.setProperty(GUI_TITLE, "Facade Pattern Demonstration");
            textSettings.setProperty(EXIT_CAPTION, "Exit");
            textSettings.setProperty(COUNTRY_LABEL, "Country");
            textSettings.setProperty(CURRENCY_LABEL, "Currency");
            textSettings.setProperty(PHONE_LABEL, "Phone Number");
            textSettings.store(new FileOutputStream("us.properties"), "US Settings");
        }
        catch (IOException exc){
            System.err.println("Error storing settings to output");
            exc.printStackTrace();
        }
    }
    private static void saveNlData(){
        try{
            Properties textSettings = new Properties();
            textSettings.setProperty(GUI_TITLE, "Facade Pattern voorbeeld");
            textSettings.setProperty(EXIT_CAPTION, "Exit");
            textSettings.setProperty(COUNTRY_LABEL, "Land");
            textSettings.setProperty(CURRENCY_LABEL, "Munt eenheid");
            textSettings.setProperty(PHONE_LABEL, "Telefoonnummer");
            textSettings.store(new FileOutputStream("dutch.properties"), "Dutch Settings");
        }
        catch (IOException exc){
            System.err.println("Error storing settings to output");
            exc.printStackTrace();
        }
    }
}
class PhoneNumber {
    private static String selectedInterPrefix;
    private String internationalPrefix;
    private String areaNumber;
    private String netNumber;
    public PhoneNumber(String intPrefix, String areaNumber, String netNumber) {
        this.internationalPrefix = intPrefix;
        this.areaNumber = areaNumber;
        this.netNumber = netNumber;
    }
    
    public String getInternationalPrefix(){ return internationalPrefix; }
    public String getAreaNumber(){ return areaNumber; }
    public String getNetNumber(){ return netNumber; }
    public static String getSelectedInterPrefix(){ return selectedInterPrefix; }
    
    public void setInternationalPrefix(String newPrefix){ internationalPrefix = newPrefix; }
    public void setAreaNumber(String newAreaNumber){ areaNumber = newAreaNumber; }
    public void setNetNumber(String newNetNumber){ netNumber = newNetNumber; }
    public static void setSelectedInterPrefix(String prefix) { selectedInterPrefix = prefix; }
    
    public String toString(){
        return internationalPrefix + areaNumber + netNumber;
    }
}
class InternationalizedText{
    private static final String DEFAULT_FILE_NAME = "";
    private Properties textProperties = new Properties();
    
    public InternationalizedText(){
        this(DEFAULT_FILE_NAME);
    }
    public InternationalizedText(String fileName){
        loadProperties(fileName);
    }
    
    public void setFileName(String newFileName){
        if (newFileName != null){
            loadProperties(newFileName);
        }
    }
    public String getProperty(String key){
        return getProperty(key, "");
    }
    public String getProperty(String key, String defaultValue){
        return textProperties.getProperty(key, defaultValue);
    }
    
    private void loadProperties(String fileName){
        try{
            FileInputStream input = new FileInputStream(fileName);
            textProperties.load(input);
        }
        catch (IOException exc){
            textProperties = new Properties();
        }
    }
}
class InternationalizationWizard{
    private HashMap map;
    private Currency currency = new Currency();
    private InternationalizedText propertyFile = new InternationalizedText();
    
    public InternationalizationWizard() {
        map = new HashMap();
        Nation[] nations = {
            new Nation("US", "$", "+1", "us.properties", NumberFormat.getInstance(Locale.US)),
            new Nation("The Netherlands", "f", "+31", "dutch.properties", NumberFormat.getInstance(Locale.GERMANY)),
            new Nation("France", "f", "+33", "french.properties", NumberFormat.getInstance(Locale.FRANCE))
        };
        for (int i = 0; i < nations.length; i++) {
            map.put(nations[i].getName(), nations[i]);
        }
    }
    
    public void setNation(String name) {
        Nation nation = (Nation)map.get(name);
        if (nation != null) {
            currency.setCurrencySymbol(nation.getSymbol());
            currency.setNumberFormat(nation.getNumberFormat());
            PhoneNumber.setSelectedInterPrefix(nation.getDialingPrefix());
            propertyFile.setFileName(nation.getPropertyFileName());
        }
    }
    
    public Object[] getNations(){
        return map.values().toArray();
    }
    public Nation getNation(String name){
        return (Nation)map.get(name);
    }
    public char getCurrencySymbol(){
        return currency.getCurrencySymbol();
    }
    public NumberFormat getNumberFormat(){
        return currency.getNumberFormat();
    }
    public String getPhonePrefix(){
        return PhoneNumber.getSelectedInterPrefix();
    }
    public String getProperty(String key){
        return propertyFile.getProperty(key);
    }
    public String getProperty(String key, String defaultValue){
        return propertyFile.getProperty(key, defaultValue);
    }
}





Facade 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.Button;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.List;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
public class DatabaseFrame extends Frame implements ActionListener,
    ItemListener {
  Database db;
  List Tables, Columns, Data;
  TextArea query;
  Button Search, Quit;
  public DatabaseFrame() {
    super("Database demonstration");
    setGUI();
    db = new Database("sun.jdbc.odbc.JdbcOdbcDriver");
    db.Open("jdbc:odbc:Grocery prices", null);
    String tnames[] = db.getTableNames();
    loadList(Tables, tnames);
    String queryText = "SELECT * from yourTableName";
    query.setText(queryText);
  }
  //------------------------------------
  private void setGUI() {
    setBackground(Color.lightGray);
    setLayout(new BorderLayout());
    Panel pn = new Panel();
    add("North", pn);
    pn.setLayout(new GridLayout(1, 3));
    pn.add(new Label("Tables"));
    pn.add(new Label("Columns"));
    pn.add(new Label("Data"));
    Panel pc = new Panel();
    add("Center", pc);
    pc.setLayout(new GridLayout(1, 3));
    pc.add(Tables = new List(15));
    pc.add(Columns = new List(15));
    pc.add(Data = new List(15));
    Tables.addItemListener(this);
    Columns.addItemListener(this);
    Panel ps = new Panel();
    add("South", ps);
    ps.add(query = new TextArea("", 3, 40));
    addPanel(ps, Search = new Button("Run Query"));
    addPanel(ps, Quit = new Button("Quit"));
    Search.addActionListener(this);
    Quit.addActionListener(this);
    setBounds(100, 100, 500, 300);
    setVisible(true);
  }
  //------------------------------------
  private void addPanel(Panel ps, Component c) {
    Panel p = new Panel();
    ps.add(p);
    p.add(c);
  }
  //------------------------------------
  private void loadList(List list, String[] s) {
    list.removeAll();
    for (int i = 0; i < s.length; i++)
      list.add(s[i]);
  }
  //------------------------------------
  public void actionPerformed(ActionEvent e) {
    Object obj = e.getSource();
    if (obj == Quit)
      System.exit(0);
    if (obj == Search)
      clickedSearch();
  }
  //------------------------------------
  public void itemStateChanged(ItemEvent e) {
    Object obj = e.getSource();
    if (obj == Tables)
      showColumns();
    if (obj == Columns)
      showData();
  }
  //------------------------------------
  private void showColumns() {
    String cnames[] = db.getColumnNames(Tables.getSelectedItem());
    loadList(Columns, cnames);
  }
  //------------------------------------
  private void showData() {
    String colname = Columns.getSelectedItem();
    String colval = db.getColumnValue(Tables.getSelectedItem(), colname);
    Data.setVisible(false);
    Data.removeAll();
    Data.setVisible(true);
    colval = db.getNextValue(Columns.getSelectedItem());
    while (colval.length() > 0) {
      Data.add(colval);
      colval = db.getNextValue(Columns.getSelectedItem());
    }
  }
  //------------------------------------
  private void clickedSearch() {
    resultSet rs = db.Execute(query.getText());
    String cnames[] = rs.getMetaData();
    Columns.removeAll();
    queryDialog q = new queryDialog(this, rs);
    q.show();
  }
  //------------------------------------
  static public void main(String argv[]) {
    new DatabaseFrame();
  }
}
class queryDialog extends Dialog implements ActionListener {
  resultSet results;
  Button OK;
  textPanel pc;
  Vector tables;
  public queryDialog(Frame f, resultSet r) {
    super(f, "Query Result");
    results = r;
    setLayout(new BorderLayout());
    OK = new Button("OK");
    Panel p = new Panel();
    add("South", p);
    p.add(OK);
    OK.addActionListener(this);
    pc = new textPanel();
    pc.setBackground(Color.white);
    add("Center", pc);
    makeTables();
    setBounds(100, 100, 500, 300);
    setVisible(true);
    repaint();
  }
  //-------------------------------------
  private void makeTables() {
    tables = new Vector();
    String t[] = results.getMetaData();
    tables.addElement(t);
    while (results.hasMoreElements()) {
      tables.addElement(results.nextElement());
    }
  }
  //-------------------------------------
  public void actionPerformed(ActionEvent e) {
    setVisible(false);
  }
  //-------------------------------------
  class textPanel extends Panel {
    public void paint(Graphics g) {
      String s[];
      int x = 0;
      int y = g.getFontMetrics().getHeight();
      int deltaX = (int) 1.5f
          * (g.getFontMetrics().stringWidth("wwwwwwwwwwwwww"));
      for (int i = 0; i < tables.size(); i++) {
        s = (String[]) tables.elementAt(i);
        for (int j = 0; j < s.length; j++) {
          String st = s[j];
          g.drawString(st, x, y);
          x += deltaX;
        }
        x = 0;
        y += g.getFontMetrics().getHeight();
        if (i == 0)
          y += g.getFontMetrics().getHeight();
      }
    }
  }
}
class Database {
  Connection con;
  resultSet results;
  ResultSetMetaData rsmd;
  DatabaseMetaData dma;
  String catalog;
  String types[];
  String database_url;
  public Database(String driver) {
    types = new String[1];
    types[0] = "TABLES"; //initialize type array
    try {
      Class.forName(driver);
    } //load the Bridge driver
    catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  //-----------------------------------
  public void close() {
    try {
      con.close();
    } catch (Exception e) {
      System.out.println("close error");
    }
  }
  //-----------------------------------
  public void Open(String url, String cat) {
    catalog = cat;
    database_url = url;
    try {
      con = DriverManager.getConnection(url);
      dma = con.getMetaData(); //get the meta data
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  //-----------------------------------
  public void reOpen() {
    try {
      con = DriverManager.getConnection(database_url);
      dma = con.getMetaData(); //get the meta data
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  //-----------------------------------
  public String[] getTableNames() {
    String[] tbnames = null;
    Vector tname = new Vector();
    //add the table names to a Vector
    //since we don"t know how many there are
    try {
      results = new resultSet(dma.getTables(catalog, null, "%", types));
    } catch (Exception e) {
      System.out.println(e);
    }
    while (results.hasMoreElements())
      tname.addElement(results.getColumnValue("TABLE_NAME"));
    //copy the table names into a String array
    tbnames = new String[tname.size()];
    for (int i = 0; i < tname.size(); i++)
      tbnames[i] = (String) tname.elementAt(i);
    return tbnames;
  }
  //-----------------------------------
  public String[] getTableMetaData() {
    // return the table type information
    results = null;
    try {
      results = new resultSet(dma.getTables(catalog, null, "%", types));
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return results.getMetaData();
  }
  //-----------------------------------
  public String[] getColumnMetaData(String tablename) {
    //return the data on a column
    results = null;
    try {
      results = new resultSet(dma.getColumns(catalog, null, tablename,
          null));
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return results.getMetaData();
  }
  //-----------------------------------
  public String[] getColumnNames(String table) {
    //return an array of Column names
    String[] tbnames = null;
    Vector tname = new Vector();
    try {
      results = new resultSet(dma.getColumns(catalog, null, table, null));
      while (results.hasMoreElements())
        tname.addElement(results.getColumnValue("COLUMN_NAME"));
    } catch (Exception e) {
      System.out.println(e);
    }
    tbnames = new String[tname.size()];
    for (int i = 0; i < tname.size(); i++)
      tbnames[i] = (String) tname.elementAt(i);
    return tbnames;
  }
  //-----------------------------------
  public String getColumnValue(String table, String columnName) {
    //return the value of a given column
    String res = null;
    try {
      if (table.length() > 0)
        results = Execute("Select " + columnName + " from " + table
            + " order by " + columnName);
      if (results.hasMoreElements())
        res = results.getColumnValue(columnName);
    } catch (Exception e) {
      System.out.println("Column value error" + columnName
          + e.getMessage());
    }
    return res;
  }
  //-----------------------------------
  public String getNextValue(String columnName) {
    // return the next value in that column
    //using the remembered resultSet
    String res = "";
    try {
      if (results.hasMoreElements())
        res = results.getColumnValue(columnName);
    } catch (Exception e) {
      System.out
          .println("next value error" + columnName + e.getMessage());
    }
    return res;
  }
  //-----------------------------------
  public resultSet Execute(String sql) {
    //execute an SQL query on this database
    results = null;
    try {
      Statement stmt = con.createStatement();
      results = new resultSet(stmt.executeQuery(sql));
    } catch (Exception e) {
      System.out.println("execute error: " + e.getMessage());
    }
    return results;
  }
}
class resultSet {
  //this class is a higher level abstraction
  //of the JDBC ResultSet object
  ResultSet rs;
  ResultSetMetaData rsmd;
  int numCols;
  public resultSet(ResultSet rset) {
    rs = rset;
    try {
      //get the meta data and column count at once
      rsmd = rs.getMetaData();
      numCols = rsmd.getColumnCount();
    } catch (Exception e) {
      System.out.println("resultset error" + e.getMessage());
    }
  }
  //-----------------------------------
  public String[] getMetaData() {
    //returns an array of all the column names
    //or other meta data
    String md[] = new String[numCols];
    try {
      for (int i = 1; i <= numCols; i++)
        md[i - 1] = rsmd.getColumnName(i);
    } catch (Exception e) {
      System.out.println("meta data error" + e.getMessage());
    }
    return md;
  }
  //-----------------------------------
  public boolean hasMoreElements() {
    try {
      return rs.next();
    } catch (Exception e) {
      System.out.println("next error " + e.getMessage());
      return false;
    }
  }
  //-----------------------------------
  public String[] nextElement() {
    //copies contents of row into string array
    String[] row = new String[numCols];
    try {
      for (int i = 1; i <= numCols; i++)
        row[i - 1] = rs.getString(i);
    } catch (Exception e) {
      System.out.println("next element error" + e.getMessage());
    }
    return row;
  }
  //-------------------------------------
  public String getColumnValue(String columnName) {
    String res = "";
    try {
      res = rs.getString(columnName);
    } catch (Exception e) {
      System.out.println("Column value error:" + columnName
          + e.getMessage());
    }
    return res;
  }
  //-------------------------------------
  public String getColumnValue(int i) {
    String res = "";
    try {
      res = rs.getString(i);
    } catch (Exception e) {
      System.out.println("Column value error: " + i + " "
          + e.getMessage());
    }
    return res;
  }
  //----------------------------------------------
  public void finalize() {
    try {
      rs.close();
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}