1. import java.util.ArrayList;
    2. import java.util.Iterator;
    3. import java.util.List;
    4. /**
    5. * @description: 责任链
    6. * @Author: wangchao
    7. * @Date: 2022/1/16
    8. */
    9. interface Interceptor {
    10. Object plugin(Object target, InterceptorChain chain);
    11. }
    12. class InterceptorA implements Interceptor {
    13. @Override
    14. public Object plugin(Object target, InterceptorChain chain) {
    15. System.out.println("InterceptorA");
    16. // 控制 InterceptorChain 是否再调一次,即迭代器是否遍历下一个
    17. return chain.plugin(target);
    18. }
    19. }
    20. class InterceptorB implements Interceptor {
    21. @Override
    22. public Object plugin(Object target, InterceptorChain chain) {
    23. System.out.println("InterceptorB");
    24. return chain.plugin(target);
    25. }
    26. }
    27. class InterceptorC implements Interceptor {
    28. @Override
    29. public Object plugin(Object target, InterceptorChain chain) {
    30. System.out.println("InterceptorC");
    31. return target;
    32. }
    33. }
    34. class InterceptorChain {
    35. private List<Interceptor> interceptorList = new ArrayList<>();
    36. private Iterator<Interceptor> iterator;
    37. public void addInterceptor(Interceptor interceptor) {
    38. interceptorList.add(interceptor);
    39. }
    40. public Object pluginAll(Object target) {
    41. for (Interceptor interceptor : interceptorList) {
    42. target = interceptor.plugin(target, this);
    43. }
    44. return target;
    45. }
    46. public Object plugin(Object target) {
    47. if (iterator == null) {
    48. iterator = interceptorList.iterator();
    49. }
    50. // 注意:这里使用 if 而不是 while,每次触发都依靠 plugin
    51. if (iterator.hasNext()) {
    52. Interceptor next = iterator.next();
    53. next.plugin(target, this);
    54. }
    55. return target;
    56. }
    57. }
    58. public class InterceptDemo {
    59. public static void main(String[] args) {
    60. Interceptor interceptorA = new InterceptorA();
    61. Interceptor interceptorB = new InterceptorB();
    62. Interceptor interceptorC = new InterceptorC();
    63. InterceptorChain interceptorChain = new InterceptorChain();
    64. interceptorChain.addInterceptor(interceptorA);
    65. interceptorChain.addInterceptor(interceptorB);
    66. interceptorChain.addInterceptor(interceptorC);
    67. interceptorChain.plugin(new Object());
    68. }
    69. }