什么是模板方法模式?摘录 wiki 的介绍。

模板设计方法存在目的在于某些算法逻辑存在一些相同处,而具体细节却不同。这样使用模板方法,可以抽取共用逻辑到父类,在子类实现具体算法细节,这样减少了重复代码。
模板方法充分运用了多态与继承。使用抽象父类定义抽象操作,然后在公共逻辑调用抽象方法。子类方法只要继承父类关注自身实现细节。

Talk is cheap. Show me the code

下面拿支付接入支付渠道例子来使用模板方法。

假设银行卡支付需要实现两家银行的支付功能。不同银行提供的接口,在参数,调用方式等肯定存在很大区别。这个时候我们就可以使用模板设计方法,父类实现支付前通用逻辑,用子类实现交互的不同。系统类结构如下。

从源码学习设计模式之模板方法-LMLPHP

AgreementPay 提供支付功能,AgreementBasePay 为抽象类实现通用逻辑,AgreementCCBPayAgreementCMBPay 实现具体的渠道支付方法。具体源码如下。

AgreementPay 接口


public interface AgreementPay {

    PayResponse payInChannel(PayReauest reauest);
}

AgreementBasePay 抽象方法实现通用逻辑。


public abstract class AgreementBasePay implements AgreementPay {

    public PayResponse pay(PayReauest reauest) {
        checkRequest(reauest);
        return this.payInChannel(reauest);
    }


    private void checkRequest(PayReauest reauest) {
        System.out.println("具体方法参数检查");
    }
}

具体实现类,实现具体渠道支付细节。


public class AgreementCCBPay extends AgreementBasePay {
    @Override
    public PayResponse payInChannel(PayReauest reauest) {
        System.out.println("去建设银行支付");
        return new PayResponse();
    }
}

public class AgreementCMBPay extends AgreementBasePay {
    @Override
    public PayResponse payInChannel(PayReauest reauest) {
        System.out.println("去招商银行支付");
        return new PayResponse();
    }
}

实现模板方法的细节,我们来看 client 使用逻辑。


public class Client {

    public static void main(String[] args) {
        System.out.println("使用招商银行支付");
        AgreementPay agreementPay = new AgreementCMBPay();
        PayRequest request = new PayRequest();
        agreementPay.payInChannel(request);
        System.out.println("使用建设银行支付");
        agreementPay = new AgreementCCBPay();
        agreementPay.payInChannel(request);
    }
}

上面 client 逻辑,其实看起来还是有一些死板,且需要外部知道调用哪个渠道接口。但是如果真正提供一个对外接口,外部调用方法是不关心你具体使用那个子类支付。所以这里我们可以改进一下,


    public static Map<String, AgreementPay> payCache = new HashMap<>();

    static {
        payCache.put("CMB", new AgreementCMBPay());
        payCache.put("CCB", new AgreementCCBPay());
    }


    public static void main(String[] args) {
        PayRequest request = new PayRequest();
        AgreementPay pa;
        switch (request.getBankCode()) {
            case "CMB":
                pa = payCache.get("CMB");
                pa.payInChannel(request);
            case "CCB":
                pa = payCache.get("CCB");
                pa.payInChannel(request);
            default:
                throw new RuntimeException();
        }

    }

改造之后我们先将其 AgreementPay 实例放入 map 中,然后调用时根据一个标志来选择具体实现类。

从上面的细节我们可以看到模板方法其实设计思路与实现细节都比较简单。看完我们的示例代码,我们去看下 mybatis 如何使用模板方法。

mybatis 模板方法应用

在看源码之前,我们先看下我们不使用 mybatis 之前,如何查询数据。


        Class.forName("com.mysql.jdbc.Driver");
        //2.获得数据库的连接
        Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD);
        //3.通过数据库的连接操作数据库,实现增删改查
        PreparedStatement pstmt = conn.prepareStatement("select user_name,age from imooc_goddess where id=?");
        pstmt.setInt(1, 21);
        ResultSet rs = pstmt.execute();

        while (rs.next()) {//如果对象中有数据,就会循环打印出来
            System.out.println(rs.getString("user_name") + "," + rs.getInt("age"));
        }

我们可以看到直接使用 JDBC 查询,十分麻烦,且需要我们自己将 java 类型转换成 jdbc 数据类型。

ORM 框架重要作用在于把数据库表与 java,ORM 框架省去我们自己将 java 类型转化成 JDBC 类型的麻烦。JDBC 存在有那么多类型,如何做到转换的那?其实关键就是应用模板设计方法。

mybatis 中存在一个接口 TypeHandler,该接口方法主要如下:


public interface TypeHandler<T> {

  void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;

  T getResult(ResultSet rs, String columnName) throws SQLException;

  T getResult(ResultSet rs, int columnIndex) throws SQLException;

  T getResult(CallableStatement cs, int columnIndex) throws SQLException;

}

从方法上看,这个接口主要的方法为 PreparedStatement 设置列参数,或者从 ResultSet 获取列的值然后转换成相应的 java 数据类型。我们看下这个接口实现的类图。

从源码学习设计模式之模板方法-LMLPHP

可以看到 BaseTypeHandlerTypeHandler 的具体抽象类,我们具体看下 TypeHandler getResult 在抽象类中实现细节。


  @Override
  public T getResult(ResultSet rs, String columnName) throws SQLException {
    T result;
    try {
      result = getNullableResult(rs, columnName);
    } catch (Exception e) {
      throw new ResultMapException("Error attempting to get column '" + columnName + "' from result set.  Cause: " + e, e);
    }
    if (rs.wasNull()) {
      return null;
    } else {
      return result;
    }
  }

   public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException;

可以看到其最后调用抽象方法 getNullableResult。其由具体的子类的实现。我们具体找一个子类 DateTypeHandler 来查看具体实现。


public class DateTypeHandler extends BaseTypeHandler<Date> {


    // 忽略其他方法
  @Override
  public Date getNullableResult(ResultSet rs, String columnName)
      throws SQLException {
    Timestamp sqlTimestamp = rs.getTimestamp(columnName);
    if (sqlTimestamp != null) {
      return new Date(sqlTimestamp.getTime());
    }
    return null;
  }

}

可见其具体从 ResultSet 取出 JDBC 类型为 Timestamp,然后转换成 java 类型的 Date

实现具体的子类,那么在哪里使用了那?其实 mybatis 框架会把所有 TypeHandler 在 TypeHandlerRegistry 注册。具体类方法如图

从源码学习设计模式之模板方法-LMLPHP

其提供了相关 register 方法注册 TypeHandler,然后又提供了相关 getTypeHandler 方法取出具体 TypeHandler 实现类。

总结

使用模板方法,将公共逻辑抽取出来,将具体实现细节交给子类。

参考

  1. Mybatis源代码分析之类型转换
12-20 06:33