当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 从源码学习设计模式之模板方法

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

2018年12月20日  | 移动技术网IT编程  | 我要评论

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

模板方法模式定义了一个算法的步骤,并允许子类别为一个或多个步骤提供其实践方式。让子类别在不改变算法架构的情况下,重新定义算法中的某些步骤。在软件工程中,它是一种软件设计模式,和c++模板没有关连。

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

talk is cheap. show me the code

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

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

系统类结构

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

agreementpay 接口

public interface agreementpay {

    payresponse payinchannel(payrequest request);
}

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

public abstract class agreementbasepay implements agreementpay {

    public payresponse pay(payrequest request) {
        checkrequest(request);
        return this.payinchannel(request);
    }


    private void checkrequest(payrequest request) {
        system.out.println("具体方法参数检查");
    }
}

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

public class agreementccbpay extends agreementbasepay {
    @override
    public payresponse payinchannel(payrequest request) {
        system.out.println("去建设银行支付");
        return new payresponse();
    }
}

public class agreementcmbpay extends agreementbasepay {
    @override
    public payresponse payinchannel(payrequest request) {
        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);
                return;
            case "ccb":
                pa = paycache.get("ccb");
                pa.payinchannel(request);
                return;
            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 数据类型。我们看下这个接口实现的类图。

typehandler 实现类图

可以看到 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 注册。具体类方法如图

typehandlerregistry

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

总结

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

参考

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网