您的位置:首页 > 其它

设计模式-代理模式(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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: