模板方法模式

模板模式都是由抽象类来定义一个算法,在算法实现的不同步骤上抽象方法由子类继承并提供具体实现,常见的就是不同步骤提供doXXX抽象方法留给子类实现。模板模式一般有两部分组成,即抽象模板和具体模板。

JDBCTemplate、RedisTemplate、MongoTemplate等均是典型的模板模式。

public abstract class JdbcTemplate {  
  
    //template method  
    public final Object execute(String sql) throws SQLException{  
          
        Connection con = HsqldbUtil.getConnection();  
        Statement stmt = null;  
        try {  
   
            stmt = con.createStatement();  
            ResultSet rs = stmt.executeQuery(sql);  
            Object result = doInStatement(rs);//abstract method   
            return result;  
        }  
        catch (SQLException ex) {  
             ex.printStackTrace();  
             throw ex;  
        }  
        finally {  
   
            try {  
                stmt.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
            try {  
                if(!con.isClosed()){  
                    try {  
                        con.close();  
                    } catch (SQLException e) {  
                        e.printStackTrace();  
                    }  
                }  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
              
        }  
    }  
      
    //implements in subclass  
    protected abstract Object doInStatement(ResultSet rs);  
}  
原文地址:https://www.cnblogs.com/whutwxj/p/15213104.html