当前位置: 移动技术网 > IT编程>开发语言>Java > Mybatis 使用的 9 种设计模式,真是太有用了~

Mybatis 使用的 9 种设计模式,真是太有用了~

2020年04月01日  | 移动技术网IT编程  | 我要评论
虽然我们都知道有26个设计模式,但是大多停留在概念层面,真实开发中很少遇到,Mybatis源码中使用了大量的设计模式,阅读源码并观察设计模式在其中的应用,能够更深入的理解设计模式。 Mybatis至少遇到了以下的设计模式的使用: 1. Builder模式,例如SqlSessionFactoryBui ...

虽然我们都知道有26个设计模式,但是大多停留在概念层面,真实开发中很少遇到,mybatis源码中使用了大量的设计模式,阅读源码并观察设计模式在其中的应用,能够更深入的理解设计模式。

mybatis至少遇到了以下的设计模式的使用:

  1. builder模式,例如sqlsessionfactorybuilder、xmlconfigbuilder、xmlmapperbuilder、xmlstatementbuilder、cachebuilder;

  2. 工厂模式,例如sqlsessionfactory、objectfactory、mapperproxyfactory;

  3. 单例模式,例如errorcontext和logfactory;

  4. 代理模式,mybatis实现的核心,比如mapperproxy、connectionlogger,用的jdk的动态代理;还有executor.loader包使用了cglib或者javassist达到延迟加载的效果;

  5. 组合模式,例如sqlnode和各个子类choosesqlnode等;

  6. 模板方法模式,例如baseexecutor和simpleexecutor,还有basetypehandler和所有的子类例如integertypehandler;

  7. 适配器模式,例如log的mybatis接口和它对jdbc、log4j等各种日志框架的适配实现;

  8. 装饰者模式,例如cache包中的cache.decorators子包中等各个装饰者的实现;

  9. 迭代器模式,例如迭代器模式propertytokenizer;

接下来挨个模式进行解读,先介绍模式自身的知识,然后解读在mybatis中怎样应用了该模式。

builder模式的定义是“将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。”,它属于创建类模式,一般来说,如果一个对象的构建比较复杂,超出了构造函数所能包含的范围,就可以使用工厂模式和builder模式,相对于工厂模式会产出一个完整的产品,builder应用于更加复杂的对象的构建,甚至只会构建产品的一个部分。


在mybatis环境的初始化过程中,sqlsessionfactorybuilder会调用xmlconfigbuilder读取所有的mybatismapconfig.xml和所有的*mapper.xml文件,构建mybatis运行的核心对象configuration对象,然后将该configuration对象作为参数构建一个sqlsessionfactory对象。

其中xmlconfigbuilder在构建configuration对象时,也会调用xmlmapperbuilder用于读取*mapper文件,而xmlmapperbuilder会使用xmlstatementbuilder来读取和build所有的sql语句。

在这个过程中,有一个相似的特点,就是这些builder会读取文件或者配置,然后做大量的xpathparser解析、配置或语法的解析、反射生成对象、存入结果缓存等步骤,这么多的工作都不是一个构造函数所能包括的,因此大量采用了builder模式来解决。

对于builder的具体类,方法都大都用build*开头,比如sqlsessionfactorybuilder为例,它包含以下方法:

即根据不同的输入参数来构建sqlsessionfactory这个工厂对象。

在mybatis中比如sqlsessionfactory使用的是工厂模式,该工厂没有那么复杂的逻辑,是一个简单工厂模式。

简单工厂模式(simple factory pattern):又称为静态工厂方法(static factory method)模式,它属于类创建型模式。在简单工厂模式中,可以根据参数的不同返回不同类的实例。简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。

sqlsession可以认为是一个工作的核心的接口,通过这个接口可以执行执行sql语句、获取mappers、管理事务。类似于连接mysql的connection对象。,这个我推荐你看下。

可以看到,该factory的opensession方法重载了很多个,分别支持autocommit、executor、transaction等参数的输入,来构建核心的sqlsession对象。

在defaultsqlsessionfactory的默认工厂实现里,有一个方法可以看出工厂怎么产出一个产品:

private sqlsession opensessionfromdatasource(executortype exectype, transactionisolationlevel level,  
     boolean autocommit) {  
   transaction tx = null;  
   try {  
     final environment environment = configuration.getenvironment();  
     final transactionfactory transactionfactory = gettransactionfactoryfromenvironment(environment);  
     tx = transactionfactory.newtransaction(environment.getdatasource(), level, autocommit);  
     final executor executor = configuration.newexecutor(tx, exectype);  
     return new defaultsqlsession(configuration, executor, autocommit);  
   } catch (exception e) {  
     closetransaction(tx); // may have fetched a connection so lets call  
                 // close()  
     throw exceptionfactory.wrapexception("error opening session.  cause: " \+ e, e);  
   } finally {  
     errorcontext.instance().reset();  
   }  
 }

这是一个opensession调用的底层方法,该方法先从configuration读取对应的环境配置,然后初始化transactionfactory获得一个transaction对象,然后通过transaction获取一个executor对象,最后通过configuration、executor、是否autocommit三个参数构建了sqlsession。

在这里其实也可以看到端倪,sqlsession的执行,其实是委托给对应的executor来进行的。

而对于logfactory,它的实现代码:

public final class logfactory {  
 private static constructor<? extends log> logconstructor;  
  
 private logfactory() {  
   // disable construction  
 }  
  
 public static log getlog(class<?> aclass) {  
   return getlog(aclass.getname());  
 }

这里有个特别的地方,是log变量的的类型是constructor<? extends log>,也就是说该工厂生产的不只是一个产品,而是具有log公共接口的一系列产品,比如log4jimpl、slf4jimpl等很多具体的log。

单例模式(singleton pattern):单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。

单例模式的要点有三个:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。单例模式是一种对象创建型模式。单例模式又名单件模式或单态模式。

在mybatis中有两个地方用到单例模式,errorcontext和logfactory,其中errorcontext是用在每个线程范围内的单例,用于记录该线程的执行环境错误信息,而logfactory则是提供给整个mybatis使用的日志工厂,用于获得针对项目配置好的日志对象。,这篇文章推荐你看下。

errorcontext的单例实现代码:

public class errorcontext {  
  
 private static final threadlocal<errorcontext> local = new threadlocal<errorcontext>();  
  
 private errorcontext() {  
 }  
  
 public static errorcontext instance() {  
   errorcontext context = local.get();  
   if (context == null) {  
     context = new errorcontext();  
     local.set(context);  
   }  
   return context;  
 }

构造函数是private修饰,具有一个static的局部instance变量和一个获取instance变量的方法,在获取实例的方法中,先判断是否为空如果是的话就先创建,然后返回构造好的对象。

只是这里有个有趣的地方是,local的静态实例变量使用了修饰,也就是说它属于每个线程各自的数据,而在instance()方法中,先获取本线程的该实例,如果没有就创建该线程独有的errorcontext。

代理模式可以认为是mybatis的核心使用的模式,正是由于这个模式,我们只需要编写mapper.java接口,不需要实现,由mybatis后台帮我们完成具体sql的执行。

代理模式(proxy pattern) :给某一个对象提供一个代 理,并由代理对象控制对原对象的引用。代理模式的英 文叫做proxy或surrogate,它是一种对象结构型模式。

代理模式包含如下角色:

  • subject: 抽象主题角色

  • proxy: 代理主题角色

  • realsubject: 真实主题角色

这里有两个步骤,第一个是提前创建一个proxy,第二个是使用的时候会自动请求proxy,然后由proxy来执行具体事务;

当我们使用configuration的getmapper方法时,会调用mapperregistry.getmapper方法,而该方法又会调用mapperproxyfactory.newinstance(sqlsession)来生成一个具体的代理:

/**  
* @author lasse voss  
*/  
public class mapperproxyfactory<t> {  
  
 private final class<t> mapperinterface;  
 private final map<method, mappermethod> methodcache = new concurrenthashmap<method, mappermethod>();  
  
 public mapperproxyfactory(class<t> mapperinterface) {  
   this.mapperinterface = mapperinterface;  
 }  
  
 public class<t> getmapperinterface() {  
   return mapperinterface;  
 }  
  
 public map<method, mappermethod> getmethodcache() {  
   return methodcache;  
 }  
  
 @suppresswarnings("unchecked")  
 protected t newinstance(mapperproxy<t> mapperproxy) {  
   return (t) proxy.newproxyinstance(mapperinterface.getclassloader(), new class\[\] { mapperinterface },  
       mapperproxy);  
 }  
  
 public t newinstance(sqlsession sqlsession) {  
   final mapperproxy<t> mapperproxy = new mapperproxy<t>(sqlsession, mapperinterface, methodcache);  
   return newinstance(mapperproxy);  
 }  
  
}

在这里,先通过t newinstance(sqlsession sqlsession)方法会得到一个mapperproxy对象,然后调用t newinstance(mapperproxy mapperproxy)生成代理对象然后返回。

而查看mapperproxy的代码,可以看到如下内容:

public class mapperproxy<t> implements invocationhandler, serializable {  
  
 @override  
 public object invoke(object proxy, method method, object\[\] args) throws throwable {  
   try {  
     if (object.class.equals(method.getdeclaringclass())) {  
       return method.invoke(this, args);  
     } else if (isdefaultmethod(method)) {  
       return invokedefaultmethod(proxy, method, args);  
     }  
   } catch (throwable t) {  
     throw exceptionutil.unwrapthrowable(t);  
   }  
   final mappermethod mappermethod = cachedmappermethod(method);  
   return mappermethod.execute(sqlsession, args);  
 }

非常典型的,该mapperproxy类实现了invocationhandler接口,并且实现了该接口的invoke方法。

通过这种方式,我们只需要编写mapper.java接口类,当真正执行一个mapper接口的时候,就会转发给mapperproxy.invoke方法,而该方法则会调用后续的sqlsession.cud>executor.execute>preparestatement等一系列方法,完成sql的执行和返回。

5、组合模式

组合模式组合多个对象形成树形结构以表示“整体-部分”的结构层次。

组合模式对单个对象(叶子对象)和组合对象(组合对象)具有一致性,它将对象组织到树结构中,可以用来描述整体与部分的关系。同时它也模糊了简单元素(叶子对象)和复杂元素(容器对象)的概念,使得客户能够像处理简单元素一样来处理复杂元素,从而使客户程序能够与复杂元素的内部结构解耦。

在使用组合模式中需要注意一点也是组合模式最关键的地方:叶子对象和组合对象实现相同的接口。这就是组合模式能够将叶子节点和对象节点进行一致处理的原因。

mybatis支持动态sql的强大功能,比如下面的这个sql:

<update id="update" parametertype="org.format.dynamicproxy.mybatis.bean.user">  
   update users  
   <trim prefix="set" prefixoverrides=",">  
       <if test="name != null and name != ''">  
           name = #{name}  
       </if>  
       <if test="age != null and age != ''">  
           , age = #{age}  
       </if>  
       <if test="birthday != null and birthday != ''">  
           , birthday = #{birthday}  
       </if>  
   </trim>  
   where id = ${id}  
</update>

在这里面使用到了trim、if等动态元素,可以根据条件来生成不同情况下的sql;

在dynamicsqlsource.getboundsql方法里,调用了rootsqlnode.apply(context)方法,apply方法是所有的动态节点都实现的接口:

public interface sqlnode {  
 boolean apply(dynamiccontext context);  
}

对于实现该sqlsource接口的所有节点,就是整个组合模式树的各个节点:

组合模式的简单之处在于,所有的子节点都是同一类节点,可以递归的向下执行,比如对于textsqlnode,因为它是最底层的叶子节点,所以直接将对应的内容append到sql语句中:

@override  
 public boolean apply(dynamiccontext context) {  
   generictokenparser parser = createparser(new bindingtokenparser(context, injectionfilter));  
   context.appendsql(parser.parse(text));  
   return true;  
 }

但是对于ifsqlnode,就需要先做判断,如果判断通过,仍然会调用子元素的sqlnode,即contents.apply方法,实现递归的解析。

@override  
 public boolean apply(dynamiccontext context) {  
   if (evaluator.evaluateboolean(test, context.getbindings())) {  
     contents.apply(context);  
     return true;  
   }  
   return false;  
 }

6、模板方法模式

模板方法模式是所有模式中最为常见的几个模式之一,是基于继承的代码复用的基本技术。关注java技术栈微信公众号,在后台回复关键字:架构,可以获取更多栈长整理的架构和设计模式干货。

模板方法模式需要开发抽象类和具体子类的设计师之间的协作。一个设计师负责给出一个算法的轮廓和骨架,另一些设计师则负责给出这个算法的各个逻辑步骤。代表这些具体逻辑步骤的方法称做基本方法(primitive method);而将这些基本方法汇总起来的方法叫做模板方法(template method),这个设计模式的名字就是从此而来。

模板类定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

在mybatis中,sqlsession的sql执行,都是委托给executor实现的,executor包含以下结构:

其中的baseexecutor就采用了模板方法模式,它实现了大部分的sql执行逻辑,然后把以下几个方法交给子类定制化完成:

protected abstract int doupdate(mappedstatement ms, object parameter) throws sqlexception;  
  
protected abstract list<batchresult> doflushstatements(boolean isrollback) throws sqlexception;  
  
protected abstract <e> list<e> doquery(mappedstatement ms, object parameter, rowbounds rowbounds,  
     resulthandler resulthandler, boundsql boundsql) throws sqlexception;

该模板方法类有几个子类的具体实现,使用了不同的策略:

  • 简单simpleexecutor:每执行一次update或select,就开启一个statement对象,用完立刻关闭statement对象。(可以是statement或preparestatement对象)

  • 重用reuseexecutor:执行update或select,以sql作为key查找statement对象,存在就使用,不存在就创建,用完后,不关闭statement对象,而是放置于map<string, statement>内,供下一次使用。(可以是statement或preparestatement对象)

  • 批量batchexecutor:执行update(没有select,jdbc批处理不支持select),将所有sql都添加到批处理中(addbatch()),等待统一执行(executebatch()),它缓存了多个statement对象,每个statement对象都是addbatch()完毕后,等待逐一执行executebatch()批处理的;batchexecutor相当于维护了多个桶,每个桶里都装了很多属于自己的sql,就像苹果蓝里装了很多苹果,番茄蓝里装了很多番茄,最后,再统一倒进仓库。(可以是statement或preparestatement对象)

比如在simpleexecutor中这样实现update方法:

@override  
public int doupdate(mappedstatement ms, object parameter) throws sqlexception {  
   statement stmt = null;  
   try {  
     configuration configuration = ms.getconfiguration();  
     statementhandler handler = configuration.newstatementhandler(this, ms, parameter, rowbounds.default, null,  
         null);  
     stmt = preparestatement(handler, ms.getstatementlog());  
     return handler.update(stmt);  
   } finally {  
     closestatement(stmt);  
   }  
 }

7、适配器模式

适配器模式(adapter pattern) :将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作,其别名为包装器(wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。

在mybatsi的logging包中,有一个log接口:

/**  
* @author clinton begin  
*/  
public interface log {  
  
 boolean isdebugenabled();  
  
 boolean istraceenabled();  
  
 void error(string s, throwable e);  
  
 void error(string s);  
  
 void debug(string s);  
  
 void trace(string s);  
  
 void warn(string s);  
  
}

该接口定义了mybatis直接使用的日志方法,而log接口具体由谁来实现呢?mybatis提供了多种日志框架的实现,这些实现都匹配这个log接口所定义的接口方法,最终实现了所有外部日志框架到mybatis日志包的适配:

比如对于log4jimpl的实现来说,该实现持有了org.apache.log4j.logger的实例,然后所有的日志方法,均委托该实例来实现。

public class log4jimpl implements log {  
  
 private static final string fqcn = log4jimpl.class.getname();  
  
 private logger log;  
  
 public log4jimpl(string clazz) {  
   log = logger.getlogger(clazz);  
 }  
  
 @override  
 public boolean isdebugenabled() {  
   return log.isdebugenabled();  
 }  
  
 @override  
 public boolean istraceenabled() {  
   return log.istraceenabled();  
 }  
  
 @override  
 public void error(string s, throwable e) {  
   log.log(fqcn, level.error, s, e);  
 }  
  
 @override  
 public void error(string s) {  
   log.log(fqcn, level.error, s, null);  
 }  
  
 @override  
 public void debug(string s) {  
   log.log(fqcn, level.debug, s, null);  
 }  
  
 @override  
 public void trace(string s) {  
   log.log(fqcn, level.trace, s, null);  
 }  
  
 @override  
 public void warn(string s) {  
   log.log(fqcn, level.warn, s, null);  
 }  
  
}

8、装饰者模式

装饰模式(decorator pattern) :动态地给一个对象增加一些额外的职责(responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活。其别名也可以称为包装器(wrapper),与适配器模式的别名相同,但它们适用于不同的场合。根据翻译的不同,装饰模式也有人称之为“油漆工模式”,它是一种对象结构型模式。

在mybatis中,缓存的功能由根接口cache(org.apache.ibatis.cache.cache)定义。关注java技术栈微信公众号,在后台回复关键字:架构,可以获取更多栈长整理的架构和设计模式干货。

整个体系采用装饰器设计模式,数据存储和缓存的基本功能由perpetualcache(org.apache.ibatis.cache.impl.perpetualcache)永久缓存实现,然后通过一系列的装饰器来对perpetualcache永久缓存进行缓存策略等方便的控制。如下图:

用于装饰perpetualcache的标准装饰器共有8个(全部在org.apache.ibatis.cache.decorators包中):

  1. fifocache:先进先出算法,缓存回收策略

  2. loggingcache:输出缓存命中的日志信息

  3. lrucache:最近最少使用算法,缓存回收策略

  4. scheduledcache:调度缓存,负责定时清空缓存

  5. serializedcache:缓存序列化和反序列化存储

  6. softcache:基于软引用实现的缓存管理策略

  7. synchronizedcache:同步的缓存装饰器,用于防止多线程并发访问

  8. weakcache:基于弱引用实现的缓存管理策略

另外,还有一个特殊的装饰器transactionalcache:事务性的缓存

正如大多数持久层框架一样,mybatis缓存同样分为一级缓存和二级缓存

  • 一级缓存,又叫本地缓存,是perpetualcache类型的永久缓存,保存在执行器中(baseexecutor),而执行器又在sqlsession(defaultsqlsession)中,所以一级缓存的生命周期与sqlsession是相同的。

  • 二级缓存,又叫自定义缓存,实现了cache接口的类都可以作为二级缓存,所以可配置如encache等的第三方缓存。二级缓存以namespace名称空间为其唯一标识,被保存在configuration核心配置对象中。

二级缓存对象的默认类型为perpetualcache,如果配置的缓存是默认类型,则mybatis会根据配置自动追加一系列装饰器。

cache对象之间的引用顺序为:

synchronizedcache–>loggingcache–>serializedcache–>scheduledcache–>lrucache–>perpetualcache

9、迭代器模式

迭代器(iterator)模式,又叫做游标(cursor)模式。gof给出的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。

java的iterator就是迭代器模式的接口,只要实现了该接口,就相当于应用了迭代器模式:

比如mybatis的propertytokenizer是property包中的重量级类,该类会被reflection包中其他的类频繁的引用到。这个类实现了iterator接口,在使用时经常被用到的是iterator接口中的hasnext这个函数。

public class propertytokenizer implements iterator<propertytokenizer> {  
 private string name;  
 private string indexedname;  
 private string index;  
 private string children;  
  
 public propertytokenizer(string fullname) {  
   int delim = fullname.indexof('.');  
   if (delim > -1) {  
     name = fullname.substring(0, delim);  
     children = fullname.substring(delim + 1);  
   } else {  
     name = fullname;  
     children = null;  
   }  
   indexedname = name;  
   delim = name.indexof('\[');  
   if (delim > -1) {  
     index = name.substring(delim + 1, name.length() - 1);  
     name = name.substring(0, delim);  
   }  
 }  
  
 public string getname() {  
   return name;  
 }  
  
 public string getindex() {  
   return index;  
 }  
  
 public string getindexedname() {  
   return indexedname;  
 }  
  
 public string getchildren() {  
   return children;  
 }  
  
 @override  
 public boolean hasnext() {  
   return children != null;  
 }  
  
 @override  
 public propertytokenizer next() {  
   return new propertytokenizer(children);  
 }  
  
 @override  
 public void remove() {  
   throw new unsupportedoperationexception(  
       "remove is not supported, as it has no meaning in the context of properties.");  
 }  
}

可以看到,这个类传入一个字符串到构造函数,然后提供了iterator方法对解析后的子串进行遍历,是一个很常用的方法类。

推荐去我的博客阅读更多:

1.

2.

3.

4.

生活很美好,明天见~

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网