策略模式的应用
MyBatis配置文件mybatis-config.xml中的节点settings中有一项配置如下:
<setting name="defaultExecutorType" value="SIMPLE" />
配置的是MyBatis在运行过程中默认的执行器Executor,此项配置的默认值就是SIMPLE,指向就是接口Executor的实现类SimpleExecutor。
通过查看源码可以看得到接口Executor的继承关系如下:
这些实现类为接口Executor的策略簇,实现了不同的执行器策略:
SimpleExecutor:普通的执行器
BatchExecutor:批处理执行器
ReuseExecutor:预处理语句重用执行器
MyBatis核心类Configuration类似于策略模式中的Context,区别于Context就是:Context维系是的传入的策略对象;Configuration是根据传入的策略对象类型,生产相应的策略对象,代码如下:
// 配置文件中setting属性为defaultExecutorType的对应Configuration属性
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
// 根据默认的执行器类型,生成相应的执行器对象
public Executor newExecutor(Transaction transaction) {
return newExecutor(transaction, defaultExecutorType);
}
// 可指定执行器类型,生成相应的执行器对象
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType &#