program 4 代理设计模式
概述
学到了《第一行代码 JAVA》的 4.7.4 接口的应用——代理设计模式(Proxy) 。代理设计模式的目的同样也是对客户隐藏复杂的实际程序操作,仅让客户关注他所关心的操作。
为了尝试这一模式,我写了一段关于买房的程序:对于买家而言,买房子就是看房、下定、买房、住房这么个过程,但实际上买房子还需要做更多的事情,比如房产信息对比、讨价还价、办证等等。后者实际上可以交给中介去做,也就是说,中介起到了Proxy的作用。对于客户而言,他们做了自己关心的几件事;而实际上,是中介拿着客户的钱,把客户做的事都给做了。
编程中,让客户的实际操作类RealOper 和代理操作类Proxy 都 implements 接口BuyHouse,RealOper中的方法和属性被加入到 Proxy 中,并在Proxy 中增加了不为客户所见但是必要的底层操作。
程序实现如下:
1. BuyHouse 接口
interface BuyHouse {
public abstract String[] buyAHouse();
}
2. 客户操作 RealOper 类
public class RealOper implements BuyHouse {
private String[] steps = new String[4];
public RealOper (){}
public String[] buyAHouse() {
this.steps[0] = "看房";
this.steps[1] = "下定";
this.steps[2] = "买房";
this.steps[3] = "入住";
return this.steps;
}
}
3. 代理 Proxy 类
public class Proxy implements BuyHouse {
private String[] steps = new String[8];
private String[] temp = new String[4];
private RealOper realOperation = null;
public Proxy(RealOper realOperation){
this.realOperation = realOperation;
}
public String[] buyAHouse() {
this.temp[0] = "(搜集房产信息)";
this.temp[1] = "(讨价还价)";
this.temp[2] = "(锁定房产)";
this.temp[3] = "(办证转接)";
for(int x = 0; x<this.realOperation.buyAHouse().length; x++){
this.steps[2*x] = this.temp[x];
this.steps[2*x+1] = this.realOperation.buyAHouse()[x];
}
return this.steps;
}
}
4. 测试
public class TestProxy {
public static void main(String[] args){
BuyHouse a = new Proxy(new RealOper());
System.out.println("(中介操作) --> 客户实操 ... :");
for(int x=0; x<a.buyAHouse().length; x++){
System.out.print(a.buyAHouse()[x]);
System.out.print(" --> ");
}
}
}
5. 结果
(中介操作) --> 客户实操 ... :
(搜集房产信息) --> 看房 --> (讨价还价) --> 下定 --> (锁定房产) --> 买房 --> (办证转接) --> 入住 -->