#Java笔记 #程序实现:代理设计模式

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. 结果

(中介操作) --> 客户实操 ... :
(搜集房产信息) --> 看房 --> (讨价还价) --> 下定 --> (锁定房产) --> 买房 --> (办证转接) --> 入住 --> 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值