代理模式 proxy:为其他对象提供一种代理,并以控制对这个对象的访问,好比经纪人和明星之间的关系,经纪人就是明星的代理类。简单的就是在方法调用前后做处理,AOP思想,好处就是不改变原来类方法的基础上,动态的添加其他方法。
代理模式的3个角色
1.抽象角色2.真实角色
3.代理角色
1.静态代理
首先要有两个角色
真实角色
代理角色
实现同一个接口
代理角色中包含真实角色的引用
代理类调用被代理类的方法。
2.动态代理---比较常用
public interface People { void eat(); }
public class Zhangsan implements People { public void eat(){ System.out.println("吃饭"); } }
代理类---需实现InvocationHandler 接口
public class PorxyHandler implements InvocationHandler { People people = null; public PorxyHandler(People people) { this.people = people; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { this.before(); method.invoke(people, args); this.after(); return null; } private void before(){ System.out.println("洗手"); } private void after(){ System.out.println("洗碗"); } }
public class Client { public static void main(String[] args) { People people = (People)Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{People.class}, new ProxyHandler(new Zhangsan())); people.eat(); } }
代理所有 jdk自带动态代理,只能代理接口,代理类用cglib
public interface People { public void eat(); }
public class Zhangsan implements People{ public void eat() { System.out.println("吃东西"); } public static void main(String[] args) { ProxyHandler handler = new ProxyHandler(new Zhangsan()); People people = (People)handler.getProxy(); people.eat(); } }
public class ProxyHandler implements InvocationHandler{ private Object target; public ProxyHandler(Object target) { this.target = target; } public Object getProxy(){ return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { before(); Object object = method.invoke(target, args); after(); return object; } public void before(){ System.out.println("之前"); } public void after(){ System.out.println("之后"); } }