标签:invoke 中介 private ble trace target null ace 设计
学习还是先从定义开始,反复的琢磨对模式的定义会让自己更深刻的记住。
代理模式定义:在某些场景下,系统中的目标对象不能被直接引用或者不适合直接引用,这时需要一个代理,起中介的作用以达到控制和增强目标对象。
代理模式分类:静态代理、动态代理。
代理模式结构:
1、抽象主题
2、真实主题
3、代理对象
上代码
静态代理
//抽象主题 public interface Target { public void display(); }
//真实主题 public class RealTarget implements Target { @Override public void display() { System.out.println("真实目标对象业务..."); } }
/** * 代理对象 */ public class ProxyTarget implements Target { private RealTarget realTarget; @Override public void display() { if(realTarget == null){ realTarget = new RealTarget(); } beforeDisplay(); realTarget.display(); afterDisplay(); } private void beforeDisplay(){ System.out.println("调用真实对象前事件..."); }; private void afterDisplay(){ System.out.println("调用真实对象后事件..."); }; }
/** * 测试 */ public class MainTest { public static void main(String[] args) { Target target = new ProxyTarget(); target.display(); } }
JDK动态代理:
/** * 代理对象 */ public class JDkProxyHandler implements InvocationHandler { private Object target; public Object getInstance(Object target) throws Exception{ this.target = target; Class<?> clazz = target.getClass(); return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { before(); Object obj = method.invoke(this.target, args); after(); return obj; } private void before(){ System.out.println("JDK代理前事件..."); } private void after(){ System.out.println("JDK代理之后事件..."); } }
/** * 测试 */ public class MainTest { public static void main(String[] args) { //Target target = new ProxyTarget(); //target.display(); try { Target target = (Target)new JDkProxyHandler().getInstance(new RealTarget()); target.display(); } catch (Exception e) { e.printStackTrace(); } } }
推荐来自“java极客技术”公共号的这篇文章写得很好
https://mp.weixin.qq.com/s/837rqRiNGXrs2wNQVHPH1Q
标签:invoke 中介 private ble trace target null ace 设计
原文地址:https://www.cnblogs.com/crazycomputers/p/11865677.html