设计模式5-外观模式(Facade)

设计模式-外观模式(Facade)

Facade一个典型应用就是数据库JDBC的应用,如下例对数据库的操作: 

public class DBCompare { 
  Connection conn = null;
  PreparedStatement prep = null;
  ResultSet rset = null; 
  try {
     Class.forName( "<driver>" ).newInstance();
     conn = DriverManager.getConnection( "<database>" );
    
     String sql = "SELECT * FROM <table> WHERE <column name> = ?";
     prep = conn.prepareStatement( sql );
     prep.setString( 1, "<column value>" );
     rset = prep.executeQuery();
     if( rset.next() ) {
        System.out.println( rset.getString( "<column name" ) );
     }
  } catch( SException e ) {
     e.printStackTrace();
  } finally {
     rset.close();
     prep.close();
     conn.close();
  }
}

 public class DBCompare { 
  String sql = "SELECT * FROM <table> WHERE <column name> = ?";   
  try {
     Mysql msql=new mysql(sql);
     prep.setString( 1, "<column value>" );
     rset = prep.executeQuery();
     if( rset.next() ) {
        System.out.println( rset.getString( "<column name" ) );
     }
  } catch( SException e ) {
     e.printStackTrace();
  } finally {
     mysql.close();
     mysql=null;
  }
}

 
 

可见非常简单,所有程序对数据库访问都是使用改接口,降低系统的复杂性,增加了灵活性.
Facade实际上是个理顺系统间关系,降低系统间耦合度的一个常用的办法。

你可能感兴趣的:(设计模式,sql,mysql,jdbc)