设计模式-代理模式(Proxy)
2017-04-13 12:42
295 查看
/** * 抽象主题(房东和中介的共同接口) * */ public interface Person { void sellHouse(); }
/** * 真实主题(房东) * */ public class HouseOwner implements Person{ @Override public void sellHouse() { System.out.println("sell House"); } }
/** * 代理对象(中介) * */ public class Agency implements Person{ private Person houseOwner;//被代理的对象(房东) Agency(Person houseOwner){ this.houseOwner = houseOwner; } @Override public void sellHouse() { System.out.println("中介代理卖房开始"); houseOwner.sellHouse(); System.out.println("中介代理卖房结束"); } }调用
//房东自己卖房 public static void test1(){ HouseOwner houseOwner = new HouseOwner(); houseOwner.sellHouse(); } //中介代理房东卖房 public static void test2(){ HouseOwner houseOwner = new HouseOwner(); Person agency = new Agency(houseOwner); agency.sellHouse(); }
代理对象与真实对象功能大量雷同,很繁琐。可以使用JDK提供了Proxy,InvocationHandler来生成代理对象。
public class MyInvocationHandler implements InvocationHandler { // 真实主题角色 private Person target; public MyInvocationHandler(Person target) { this.target = target; } // 调用Proxy.newProxyInstance(...)时会自动调用这个invoke方法 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("准备"); Object ret = method.invoke(target, args);// 调用target.xxx(args) System.out.println("结束"); return ret; } }
//目标对象 HouseOwner houseOwner = new HouseOwner(); //目标对象的代理对象 Person agency = (Person) Proxy.newProxyInstance( Person.class.getClassLoader(), new Class[] { Person.class }, new MyInvocationHandler(houseOwner)); agency.sellHouse();
相关文章推荐
- 设计模式之Proxy代理模式
- 设计模式(6)-代理模式(Proxy)
- 设计模式之Proxy(代理)
- NET常用设计模式——代理(Proxy)模式
- 设计模式--代理模式(Proxy Model)
- 设计模式----Proxy(代理)模式
- 设计模式之Proxy(代理)
- 设计模式学习笔记(十三)——Proxy代理模式
- 设计模式之Proxy(代理)
- Java设计模式:Proxy(代理)
- 设计模式与泡mm的关系之Proxy代理模式及代理模式的再思考
- 设计模式 --- 代理模式(Proxy) 精选经验合集
- 设计模式之代理模式(Proxy)
- 设计模式之代理(Proxy)----对象结构型模式
- 设计模式之Proxy(代理)
- Java设计模式:Proxy(代理)
- 设计模式袖珍版 连续转载之 - Proxy(代理)
- 设计模式之Proxy(代理)
- 设计模式之Proxy(代理)
- 设计模式(8)-代理模式(Proxy)