import java.util.ArrayList;import java.util.Iterator;import java.util.List;/** * @description: 责任链 * @Author: wangchao * @Date: 2022/1/16 */interface Interceptor { Object plugin(Object target, InterceptorChain chain);}class InterceptorA implements Interceptor { @Override public Object plugin(Object target, InterceptorChain chain) { System.out.println("InterceptorA"); // 控制 InterceptorChain 是否再调一次,即迭代器是否遍历下一个 return chain.plugin(target); }}class InterceptorB implements Interceptor { @Override public Object plugin(Object target, InterceptorChain chain) { System.out.println("InterceptorB"); return chain.plugin(target); }}class InterceptorC implements Interceptor { @Override public Object plugin(Object target, InterceptorChain chain) { System.out.println("InterceptorC"); return target; }}class InterceptorChain { private List<Interceptor> interceptorList = new ArrayList<>(); private Iterator<Interceptor> iterator; public void addInterceptor(Interceptor interceptor) { interceptorList.add(interceptor); } public Object pluginAll(Object target) { for (Interceptor interceptor : interceptorList) { target = interceptor.plugin(target, this); } return target; } public Object plugin(Object target) { if (iterator == null) { iterator = interceptorList.iterator(); } // 注意:这里使用 if 而不是 while,每次触发都依靠 plugin if (iterator.hasNext()) { Interceptor next = iterator.next(); next.plugin(target, this); } return target; }}public class InterceptDemo { public static void main(String[] args) { Interceptor interceptorA = new InterceptorA(); Interceptor interceptorB = new InterceptorB(); Interceptor interceptorC = new InterceptorC(); InterceptorChain interceptorChain = new InterceptorChain(); interceptorChain.addInterceptor(interceptorA); interceptorChain.addInterceptor(interceptorB); interceptorChain.addInterceptor(interceptorC); interceptorChain.plugin(new Object()); }}