利用組合方法模式重構方法體

利用組合方法模式重構方法,組合方法模式,要求所有的共有方法讀起來像一系列執行步驟的概要,而這些步驟的真正實現細節是在私有方法裏面。下面看一段沒有用組合方法模式去重構過的代碼片段:
public void populate() throws ClassNotFoundException, SQLException{
List partList = new ArrayList();
Connection connection = null;
String driverClass = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost:3306/test?user=root&password=root&useUnicode=true&characterEncoding=utf-8”;
String user = “root”;
String password = “root”;
String sql = “select istaffid,sstaffname from staff”;
try{
Class.forName(driverClass);
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
Part p = new Part();
p.setName(rs.getString(“name”));
p.setBrand(rs.getString(“brand”));
p.setRetailPrice(rs.getDouble(“retailPrice”));
partList.add(p);
}
}finally{
connection.close();
}
}

這段代碼很簡單,從數據庫中獲取連接、查庫、循環結果集並把相應字段設到Part對象中,最後把Part對象放到partList中。整段代碼的工作流程非常簡單,運行起來也沒發現什麼問題,但是這樣就代表代碼沒有問題了嗎?作爲一個開發人員,不應該就這點要求,代碼能運行不報錯就算完成,而應該是儘量寫出質量更高,更健壯的代碼。像以上的代碼複用性非常差,在方法內連接數據庫,這樣要是其它的方法也要連接數據庫,也得寫一遍類似的連接數據庫代碼,顯然會增加系統的重複代碼。因此以上方法可以進行重構。
剛纔的代碼片段,可以按照組合方法進行重構:
把獲取數據庫連接的代碼抽取到一個方法中:
private Connection getConnection() throws SQLException, ClassNotFoundException{
    String driverClass = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/test?user=root&password=root&useUnicode=true&characterEncoding=utf-8";
    String user = "root";
    String password = "root";Class.forName(driverClass);
    return DriverManager.getConnection(url, user, password);
}

接着可以抽取獲取結果集的代碼到一個方法中:
private ResultSet getResultSet(Connection connection) throws SQLException, ClassNotFoundException{
    Statement stmt = connection.createStatement();
    return stmt.executeQuery(sql);
}

循環結果集對Part對象設置也可以抽取到一個方法中:
private void addEntryToListFromResultSet(ResultSet rs) throws SQLException{
    Part p = new Part();
    p.setName(rs.getString("name"));
    p.setBrand(rs.getString("brand"));
    p.setRetailPrice(rs.getDouble("retailPrice"));
    partList.add(p);
}

然後populate方法可以這樣調用剛纔抽取的方法:
public void populate() throws ClassNotFoundException, SQLException{
    Connection connection = null;
    try{
        connection = getConnection();
        ResultSet rs = getResultSet(connection);
        while(rs.next()) addEntryToListFromResultSet(rs);
    }finally{
        connection.close();
    }
}

現在populate方法看上去簡潔多了,而且易讀性更高,這樣就符合組合方法模式的原則了-共有方法讀起來像一系列執行步驟的概要,而這些步驟的真正實現細節是在私有方法裏面。
但是重構到這裏還不算太好,因爲現在的數據庫連接還在populate方法所在的類內,要是這樣要做到很好的代碼複用,那麼子類就需要繼承populate方法所在的類,但是這樣不太適合,因爲populate方法所在的類或者還有其它邏輯。所以我們應該把數據庫相關的操作(getConnection()、getResultSet())抽取到父類中,populate()方法也可以利用模板方法模式抽取到父類,這樣子類只要繼承抽取出來的父類,就可以對數據庫進行操作,而子類就可以實現自己的邏輯。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章