熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

如何重構出DAO模式

2022-06-13   來源: Java核心技術 

  一前言
    本文的目的是將一個獲取數據庫連接的普通類重構成DAO+Abstract Factory模式
    二設計初衷
    使用數據訪問對象(DAOData Access Object)模式來抽象和封裝所有對數據源的訪問DAO管理著與數據源的連接以便檢索和存儲數據可以降低商業邏輯層和數據訪問層的耦合度提高應用的可維護性和可移植性
    由於底層數據源實現變化時DAO向客戶端提供的接口不會變化所有該模式允許DAO調整到不同的存儲模式而不會影響其客戶端或者業務組件顯然DAO充當了組件和數據源之間的適配器
    三重構
    首先創建一個獲取數據庫連接的普通類
    DAOClientjava
    import javasql*;
    publicclass DAOClient {
        publicstaticvoid main( String[] args ) {
           try {
               //For Oracle
               ClassforName( oraclejdbcdriverOracleDriver );
               Connection conn = DriverManagergetConnection(
                      jdbc:oracle:thin:@localhost::dy scott tiger );
               Systemoutprintln( conntoString() );
           } catch ( ClassNotFoundException e ) {
               eprintStackTrace();
           } catch ( SQLException e ) {
               eprintStackTrace();
           }
        }
    }

  再將這段代碼封裝到一個getConnection()方法中以便其它的地方調用
    import javasql*;
    publicclass DAOClient {
        publicstaticvoid main( String[] args ) {
           Connection conn = getConnection();
           Systemoutprintln( conntoString() );
        }
        /**
         *得到一個Connection對象
         *@returnjavasqlConnection
         */
        privatestatic Connection getConnection() {
           Connection conn = null;
           try {
               //For Oracle
               ClassforName( oraclejdbcdriverOracleDriver );
               conn = DriverManagergetConnection(
                      jdbc:oracle:thin:@localhost::dy scott tiger );
           } catch ( ClassNotFoundException e ) {
               eprintStackTrace();
           } catch ( SQLException e ) {
               eprintStackTrace();
           }
           return conn;
        }
    }

  再將此方法定義到針對Oracle的工廠類中
    OracleDAOFactoryjava
    import javasql*;
    publicclass OracleDAOFactory {
        private OracleDAOFactory() {}
        /**
         *返回一個OracleDAOFactory對象
         *@returnOracleDAOFactory類型對象
         */
        publicstatic OracleDAOFactory newInstance() {
           returnnew OracleDAOFactory();
        }
        /**
         *得到一個Connection對象
         *@returnjavasqlConnection
         */
        public Connection getConnection() {
           Connection conn = null;
           try {
               //For Oracle
               ClassforName( oraclejdbcdriverOracleDriver );
               conn = DriverManagergetConnection(
                      jdbc:oracle:thin:@localhost::dy scott tiger );
           } catch ( ClassNotFoundException e ) {
               eprintStackTrace();
           } catch ( SQLException e ) {
               eprintStackTrace();
           }
           return conn;
        }
    }

  此時DAOClientjava這個測試類的代碼應修改為
    import javasql*;
    public class DAOClient {
        publicstaticvoid main( String[] args ) {
           Connection conn = OracleDAOFactorynewInstance()getConnection();
           Systemoutprintln( conntoString() );
        }
    }

  考慮通常數據庫服務器數據庫名數據庫用戶密碼等應該從配置文件中獲取因此修改Oracle的工廠類
    import javaioIOException;
    import javasqlConnection;
    import javasqlDriverManager;
    import javasqlSQLException;
    import javautilProperties;
    publicclass OracleDAOFactory {
        privatestatic Properties prop = new Properties();
        static {
           try {
               propload( OracleDAOFactoryclass
                      getResourceAsStream( configproperties ) );
           } catch ( IOException e ) {
               Systemoutprintln( File:configproperties no findPLS check out! );
               eprintStackTrace();
           }
        }
        private String CONNECTION_SERVER_NAME = prop
               getProperty( oracle_server_name );
        private String CONNECTION_DRIVER = propgetProperty( oracle_conn_driver );
        private String CONNECTION_DBINSTANCE = prop
               getProperty( oracle_dbInstance );
        private String CONNECTION_USER = propgetProperty( oracle_conn_user );
        private String CONNECTION_PWD = propgetProperty( oracle_conn_pwd );
        private String CONNECTION_URL = jdbc:oracle:thin:@
               + CONNECTION_SERVER_NAME + :: + CONNECTION_DBINSTANCE;

  private OracleDAOFactory() {}
        /**
         *返回一個OracleDAOFactory對象
         *@returnOracleDAOFactory類型對象
         */
        publicstatic OracleDAOFactory newInstance() {
           returnnew OracleDAOFactory();
        }
        /**
         *得到一個Connection對象
         *@returnjavasqlConnection
         */
        public Connection getConnection() {
           Connection conn = null;
           try {
               ClassforName( CONNECTION_DRIVER );
               conn = DriverManagergetConnection(
                      CONNECTION_URL CONNECTION_USER CONNECTION_PWD );
           } catch ( ClassNotFoundException e ) {
               eprintStackTrace();
           } catch ( SQLException e ) {
               eprintStackTrace();
           }
           return conn;
        }
    }

  添加配置文件configproperties
    oracle_server_name=localhost
    oracle_conn_driver=oraclejdbcdriverOracleDriver
    oracle_dbInstance=dy
    oracle_conn_user=scott
    oracle_conn_pwd=tiger

  繼續考慮客戶端在獲取數據庫連接時使用的是針對Oracle的數據庫的工廠但如果數據庫變化了那麼客戶端的代碼還是要改變因此可以定義一個DAOFactory類定義了一個抽象方法getConnection()用於獲取數據庫連接還有一個getDAOFactory()方法根據參數dbType的值返回不同的DAOFactory
    DAOFactoryjava
    import javasqlConnection;
    publicabstractclass DAOFactory {
        publicstaticfinalintORACLE = ;
        publicstaticfinalintSQLSERVER = ;
        publicstaticfinalintMYSQL = ;

  public abstract Connection getConnection();

  publicstatic DAOFactory getDAOFactory( int dbType ) {
           switch( dbType ) {
           caseORACLE:
               return OracleDAOFactorynewInstance();
           caseSQLSERVER:
               return SqlDAOFactorynewInstance();
           caseMYSQL:
               return MySqlDAOFactorynewInstance();
           default:
               returnnull;
           }
        }
    }

  SqlDAOFactoryjava
    import javaioIOException;
    import javasqlConnection;
    import javasqlDriverManager;
    import javasqlSQLException;
    import javautilProperties;
    publicclass SqlDAOFactory extends DAOFactory {
        privatestatic Properties prop = new Properties();
        static {
           try {
               propload( OracleDAOFactoryclass
                      getResourceAsStream( configproperties ) );
           } catch ( IOException e ) {
               Systemoutprintln( File:configproperties no findPLS check out! );
               eprintStackTrace();
           }
        }
        private String CONNECTION_SERVER_NAME = prop
               getProperty( sqlserver_server_name );
        private String CONNECTION_DRIVER = propgetProperty( sqlserver_conn_driver );
        private String CONNECTION_DBINSTANCE = prop
               getProperty( sqlserver_dbInstance );
        private String CONNECTION_USER = propgetProperty( sqlserver_conn_user );
        private String CONNECTION_PWD = propgetProperty( sqlserver_conn_pwd );
        private String CONNECTION_URL = jdbc:microsoft:sqlserver://
               + CONNECTION_SERVER_NAME + :;DatabaseName=
               + CONNECTION_DBINSTANCE;

  private SqlDAOFactory() {}
        /**
         *返回一個SqlDAOFactory對象
         *@returnSqlDAOFactory類型對象
         */
        publicstatic SqlDAOFactory newInstance() {
           returnnew SqlDAOFactory();
        }
        /**
         *得到一個Connection對象
         *@returnjavasqlConnection
         */
        public Connection getConnection() {
           Connection conn = null;
           try {
               ClassforName( CONNECTION_DRIVER );
               conn = DriverManagergetConnection(
                      CONNECTION_URL CONNECTION_USER CONNECTION_PWD );
           } catch ( ClassNotFoundException e ) {
               eprintStackTrace();
           } catch ( SQLException e ) {
               eprintStackTrace();
           }
           return conn;
        }
    }

  MySqlDAPFactoryjava
    import javaioIOException;
    import javasqlConnection;
    import javasqlDriverManager;
    import javasqlSQLException;
    import javautilProperties;
    publicclass MySqlDAOFactory extends DAOFactory {
        privatestatic Properties prop = new Properties();
        static {
           try {
               propload( OracleDAOFactoryclass
                      getResourceAsStream( configproperties ) );
           } catch ( IOException e ) {
               Systemoutprintln( File:configproperties no findPLS check out! );
               eprintStackTrace();
           }
        }
        private String CONNECTION_SERVER_NAME = prop
               getProperty( mysql_server_name );
        private String CONNECTION_DRIVER = propgetProperty( mysql_conn_driver );
        private String CONNECTION_DBINSTANCE = prop
               getProperty( mysql_dbInstance );
        private String CONNECTION_USER = propgetProperty( mysql_conn_user );
        private String CONNECTION_PWD = propgetProperty( mysql_conn_pwd );
        private String CONNECTION_URL = jdbc:mysql://
               + CONNECTION_SERVER_NAME + :/ + CONNECTION_DBINSTANCE
               + ?useUnicode=true&characterEncoding=UTF;

  private MySqlDAOFactory() {}
        /**
         *返回一個MySqlDAOFactory對象
         *@returnMySqlDAOFactory類型對象
         */
        publicstatic MySqlDAOFactory newInstance() {
           returnnew MySqlDAOFactory();
        }
        /**
         *得到一個Connection對象
         *@returnjavasqlConnection
         */
 

  public Connection getConnection() {
           Connection conn = null;
           try {
               ClassforName( CONNECTION_DRIVER );
               conn = DriverManagergetConnection(
                      CONNECTION_URL CONNECTION_USER CONNECTION_PWD );
           } catch ( ClassNotFoundException e ) {
               eprintStackTrace();
           } catch ( SQLException e ) {
               eprintStackTrace();
           }
           return conn;
        }
    }

  修改configproperties配置文件
    #Oracle
    oracle_server_name=localhost
    oracle_conn_driver=oraclejdbcdriverOracleDriver
    oracle_dbInstance=dy
    oracle_conn_user=scott
    oracle_conn_pwd=tiger

  #SqlServer
    sqlserver_server_name=localhost
    sqlserver_conn_driver=commicrosoftjdbcsqlserverSQLServerDriver
    sqlserver_dbInstance=test
    sqlserver_conn_user=sa
    sqlserver_conn_pwd=sa

  #MySql
    mysql_server_name=localhost
    mysql_conn_driver=commysqljdbcDriver
    mysql_dbInstance=test
    mysql_conn_user=root
    mysql_conn_pwd=root

  最後修改客戶端文件DAOClientjava代碼
    import javasql*;
    public class DAOClient {
        public static void main( String[] args ) {
           DAOFactory dao = DAOFactorygetDAOFactory( DAOFactoryORACLE );
           Connection conn = daogetConnection();
           Systemoutprintln( conntoString() );
        }
    }

  通過這種DAO+(Abstract)Factory方式在將程序遷移到其它數據庫中時在客戶端程序中幾乎不用做修改唯一需要做的就是在獲得DAOFactory對象的時候修改相應的參數例如遷移到MySql下的時候
    DAOFactory dao = DAOFactorygetDAOFactory( DAOFactoryMYSQL );


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26544.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.