设计模式 Facade模式
Facade模式的定义: 为子系统中的一组接口提供一个一致的界面.Facade一个典型应用就是数据库JDBC的应用,如下例对数据库的操作:说明:这是在网上的一篇文章中看到的列子,上面没有写全,我在这里补上了,没有用到接口。package com.pattern.structural.facade;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;/* * 外观模式的主要用途就是为子系统的复杂处理过程提供方便的调用方法, * 使得子系统更加容易被使用。 * Facade对象通常属于Singleton模式。*/public class Mysql { private static Connection conn=null; private static PreparedStatement prep=null; public Mysql(String sql) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root",""); prep = conn.prepareStatement(sql); } catch (Exception e) { e.printStackTrace(); } } public void setString(int index, String parString) { try { prep.setString(index, parString); } catch (SQLException e) { e.printStackTrace(); } } public ResultSet executeQuery() { try { return prep.executeQuery(); } catch (SQLException e) { e.printStackTrace(); return null; } } public void close() { try { conn.close(); prep.close(); } catch (SQLException e) { e.printStackTrace(); } }}package com.pattern.structural.facade;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;public class DBCompare { public void getResultSet(String sql) {// String sql = "SELECT * FROM bulletin WHERE id = ?"; Mysql mysql = new Mysql(sql); try { mysql.setString(1, "4"); ResultSet rset = mysql.executeQuery(); while (rset.next()) { System.out.println(rset.getString("id")); } } catch (Exception e) { e.printStackTrace(); } finally { mysql.close(); mysql = null; } }}package com.pattern.structural.facade;import java.sql.ResultSet;public class FacadeTest { public static void main(String[] args) { Mysql mysql = new Mysql("SELECT * FROM bulletin"); try { ResultSet rset = mysql.executeQuery(); while (rset.next()) { System.out.println(rset.getString("id")); } } catch (Exception e) { e.printStackTrace(); } finally { mysql.close(); mysql = null; } }}