Mybatis插件-责任链模式

责任链模式:将完整的、臃肿的接受者的实现逻辑拆分到多个只包含部分逻辑的、功能单一的Handler处理类中,开发人员可以根据业务需求将多个Handler对象组合成一条责任链,实现请求的处理。在一条责任链中,每个Handler对象都包含对下一个Handler对象的引用,一个Hanlder对象处理完请求消息(或不能处理该请求)时,会把请求传给下一个Handler对象继续处理,依次类推,直至整条责任链结束。
Mybatis插件-责任链模式
场景:消息中有ABC三个字段,接受者HandlerA,HandlerB,HandlerC分别实现了处理三个字段的业务逻辑,当业务需要处理AC两个字段时,开发人员可以动态组合得到HandlerA->HandlerC这条责任链,为了在请求消息中承载更多信息,则通过添加D字段的方式对请求消息进行升级,接收者一端可以添加HandlerD类负责处理字段D,并动态组合得到HandlerA->HanlderC->HanlderD这条责任链。可以动态改动责任链内的Handler对象的组合顺序或动态新增、删除Handler对象,满足新的需求,可以提高系统的灵活性。
插件实际上是通过Interceptor实现的,Mybatis的插件模块中设计责任链模式和JDK动态代理。

Mybatis插件-责任链模式

/**
 *    Copyright 2009-2019 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.plugin;

import java.util.Properties;

/**
 * @author Clinton Begin
 */
public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;

  default Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }

  default void setProperties(Properties properties) {
    // NOP
  }

}

/**
 *    Copyright 2009-2019 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.plugin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Clinton Begin
 */
public class InterceptorChain {

  private final List<Interceptor> interceptors = new ArrayList<>();

  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }

  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

}

上一篇:modelsim经常破解失败


下一篇:车牌号-地区关系表