Skip to content

Latest commit

 

History

History
72 lines (51 loc) · 1.87 KB

动态代理.md

File metadata and controls

72 lines (51 loc) · 1.87 KB

动态代理

动态最常见的调用方式

    ITestListenter testBp=new BpTestListner();
    ITestListenter bpBproxy=(ITestListenter)new ProxyUtil(testBp).getProxyInstance();

分析调用方式

从调用的方式来看,
ITestListenter 规范了接口的行为

BpTestListner 实现了行为,但BpTestListner并不直接的执行者,在BpTestListner中可以替换具体的执行者。BpTestListner只是代理了它的行为。

ProxyUtil 类的构造方法传入是具体的执行者,ProxyUtil的实现方式是通过java提供的Proxy类及InvocationHandler类。

ProxyUtil类

public class ProxyUtil {
    private Object target;

    public ProxyUtil(Object target) {
        this.target = target;
    }

    public  Object  getProxyInstance() {
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("开启事务");

                // 执行目标对象方法
                Object returnValue = method.invoke(target, args);

                System.out.println("提交事务");
                return null;
            }
        };
        return Proxy.newProxyInstance(
				target.getClass().getClassLoader(), 
				target.getClass().getInterfaces(),
				invocationHandler);
    }

}

定义接口

public interface ITestListenter {
    public void test();
}

实现接口

public class BpTestListner implements ITestListenter {
    EcgHandler ecgHandler = new EcgHandler();//具体的执行者

    @Override
    public void test() {
        ecgHandler.test();
    }
}

从这里可以看出来,EcgHandler 通过Proxy被BpTestListner代理了它的具体行为,
以后要替换只需要修改 BpTestListner中的实现类就好了。