Java中的反射与代理(2)
在经典的GoF设计模式中,有一种模式叫做代理模式,好比以前洋务运动的时候所说的「买办」,还有现在咱们经常听到的「代理人」战争中的「代理」,都是同一个意思——代替某人打理。
例如,很多北漂都找中介或者二房东租过房子,还有倒卖iPhone的黄牛党,对于租房的房客和房东、买iPhone的消费者和苹果公司来说,这些中介或者黄牛,就是对方的代理人,因为他们(买家或卖家)根本不关心谁在和自己交易,只要实现交易即可,而且也免去了一个个对接的麻烦,就像这样:

这个是最普通的代理,也称为「静态」代理,如果用代码来描述,就是:
/**
* 需要代理的行为
*/
public interface Renting {
// 租房
public void renthouse();
}
/**
* 买方行为
*/
public class Consumer implements Renting {
@Override
public void renthouse() {
System.out.println("租客租房");
}
}
/**
* 代理实现
*/
public class RentingProxy implements Renting {
private Renting renting;
public RentingProxy(Renting renting) {
this.renting = renting;
}
@Override
public void renthouse() {
System.out.println("代理方法前置:租房前看房");
renting.renthouse();
System.out.println("代理方法后置:满意签合同");
}
public static void main(String[] args) {
Consumer consumer = new Consumer();
consumer.renthouse();
System.out.println("===================");
Renting proxy = new RentingProxy(consumer);
proxy.renthouse();
}
}


