首先通过一张图了解一下代理模式
在这里:中介就是一个代理人,帮助房东实现出租房屋的功能,这就是静态代理的实现。
然后看代码
房东类
package com.xiaobai.proxy;
/**
* 房东 出租角色
*/
public class Landlord implements Rent{
@Override
public void rent() {
System.out.println("我是房东 我房屋租出");
}
}
代理类 房屋中介
package com.xiaobai.proxy;
/**
* 代理角色 房屋中介
*/
public class HousingAgency implements Rent{
private Rent rent;
public HousingAgency() {
}
public HousingAgency(Rent rent) {
this.rent = rent;
}
@Override
public void rent() {
// 看房
see();
// 合同
contract();
// 收费
pay();
// 转交房租
give();
// 成功租房
rent.rent();
}
/**
* 看房
* @return boolean
*/
private boolean see(){
System.out.println("中介带房客看房,房客觉得可以,就租房,不可以就拜拜");
return true;
}
/**
* 签合同
* @return boolean
*/
private boolean contract(){
System.out.println("签合同,如果没有霸王条款则正常签订");
return true;
}
/**
* 交钱
* @return boolean
*/
private boolean pay(){
System.out.println("签订完合同交房租");
return true;
}
/**
* 中介将房租转给房东
* @return 返回一张收据
*/
private String give(){
System.out.println("转交房租给房东");
return "房东已收到钱";
}
}
房东和中介都要完成的动作——租房
package com.xiaobai.proxy;
public interface Rent {
// 出租房屋方法
public void rent();
}
来租房的客户
package com.xiaobai.proxy;
/**
* 房客 承租角色
*/
public class Tenant {
public static void main(String[] args) {
// 创建真实的房东对象
Landlord landlord = new Landlord();
// 创建代理对象并代理房东出租
HousingAgency housingAgency = new HousingAgency(landlord);
// 将房屋出租
housingAgency.rent();
}
}
运行结果
静态代理模式优点:
- 分解角色功能,使真实角色(房东)更加纯粹
- 真正的租房是由中介完成的,使业务集中在中介类,业务更加纯粹
- 中介可以帮助房东完成各项事务,便于扩展业务,而且业务发生改变时便于集中管理
缺点:
- 每有一个角色就要有一个代理,代码量翻倍且大多冗余