欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式-责任链'Chain Of Responsiblity'

程序员文章站 2024-03-23 15:46:52
...

Mybatis中的Plugin是依赖Interceptor接口实现的,这里面还用到了责任链模式 Chain of responsibility

interceptorChain.addInterceptor(interceptor);


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);
  }
}

上面的InterceptorChain在调用pluginAll的时候会应用所有的plugin

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

具体的就是,依次生成JDK dynamic proxy对象,并且将对具体statement的调用应用拦截器,形成调用链,及责任链模式。

如图所示
设计模式-责任链'Chain Of Responsiblity'

举个栗子:

# Reviewer基础类
public abstract class Reviewer {
    public Reviewer nextReviewer;
    Reviewer addReviewer(Reviewer nextReviewer){
        return this.nextReviewer=nextReviewer;
    }
    
    abstract void reviewCode(String code);
    public void review(String code){
        reviewCode(code);
        if(nextReviewer!=null){
            nextReviewer.review(code);
        }
    }
}
#几种实现
public class SelfReview extends Reviewer {
    @Override
    public void reviewCode(String code) {
        System.out.println(code + " \n self review done \n");
    }
}
public class PeerReviewer extends Reviewer {
    @Override
    public void reviewCode(String code) {
        System.out.println(code + " \n peer review done \n");
    }
}
public class TeamLeadReviewer extends Reviewer {
    @Override
    public void reviewCode(String code) {
        System.out.println(code + "\n team lead review done \n");
    }
}
#测试
public static void main(String[] args){
    String code = "hello world";
    Reviewer selfReviewer = new SelfReview();
    Reviewer peerReviewer = new PeerReviewer();
    Reviewer teamLeadReviewer = new TeamLeadReviewer();
    selfReviewer.addReviewer(peerReviewer);
    peerReviewer.addReviewer(teamLeadReviewer);
    selfReviewer.review("Hello world");
}

责任链的作用很明显了,解藕,可以在sender和receiver之间添加更多的逻辑