02-(行为型)设计模式:责任链模式

2022-10-31  本文已影响0人  XAbo

将请求的发送者和接收者解耦,使的多个对象都有处理这个请求的机会。

典型案例:Spring的MethodInterceptor环绕通知的实现。

public class MyMethodInterceptor {

    static class Target {
        public void foo() {
            System.out.println("foo---");
        }
    }

    static class Advice1 implements MethodInterceptor {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            System.out.println("Advice1---before");
            Object result = invocation.proceed();
            System.out.println("Advice1---after");
            return result;
        }
    }

    static class Advice2 implements MethodInterceptor {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            System.out.println("Advice2---before");
            Object result = invocation.proceed();
            System.out.println("Advice2---after");
            return result;
        }
    }

    static class MyInvocation implements MethodInvocation {
        private Object target;
        private Method method;
        private Object[] args;
        List<MethodInterceptor> methodInterceptorList;
        int count = 1;

        public MyInvocation(Object target, Method method, Object[] args, List<MethodInterceptor> methodInterceptorList) {
            this.target = target;
            this.method = method;
            this.args = args;
            this.methodInterceptorList = methodInterceptorList;
        }

        @Override
        public Method getMethod() {
            return method;
        }

        @Override
        public Object[] getArguments() {
            return args;
        }

        // 调用链的核心:使用递归
        @Override
        public Object proceed() throws Throwable {
            if (count > methodInterceptorList.size()) {
                return method.invoke(target, args);
            }
            MethodInterceptor methodInterceptor = methodInterceptorList.get(count++ - 1);
            return methodInterceptor.invoke(this);
        }

        @Override
        public Object getThis() {
            return target;
        }

        @Override
        public AccessibleObject getStaticPart() {
            return method;
        }
    }

    public static void main(String[] args) throws Throwable {
        Target target =  new  Target();
        List<MethodInterceptor> list =  new ArrayList<>();
        list.add(new Advice1());
        list.add(new Advice2());
        MyInvocation  invocation = new  MyInvocation(target,Target.class.getMethod("foo"), new Object[0],list);
        invocation.proceed();
    }

}

结果:

Advice1---before
Advice2---before
foo---
Advice2---after
Advice1---after
上一篇 下一篇

猜你喜欢

热点阅读