模板方法

1. 使用场景

spring中大量采用这种模式来简化重复的代码。

2. 实现举例

例如,在执行jdbc操作时,获取连接、创建Statement、执行sql、关闭Statement、关闭连接,这一系列操作的顺序和调用方式都是一致的,因此就把这些一系列操作的代码封装为一个模板方法:

public class JdbcTemplate {

  public void execute(String sql) {
    Connection conn = null;
    Statement stmt = null;
    try {
      conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
      stmt = conn.createStatement();
      stmt.execute(sql);
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      if(stmt!=null)
        try { stmt.close(); } catch (SQLException e) { }
      if(conn!=null)
        try { conn.close(); } catch (SQLException e) { }
    }
  }

}

以后调用时使用:

JdbcTemplate jt = new JdbcTemplate();
jt.execute("insert into ...");
jt.execute("update ...");
jt.execute("delete ...");

可以让使用者只需要关注具体sql,而不是整个jdbc操作的所有步骤。


results matching ""

    No results matching ""