首页 > 代码库 > java设计模式--代理模式
java设计模式--代理模式
代理模式 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(); }}
java设计模式--代理模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。