角色分析:
- 抽象角色:一般会使用接口或者抽象类解决
- 真是角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色之后,我们一般会做一些附属操作
- 客户:访问代理对象的人
代码步骤:
1、 接口
public interface Rent {
public void rent();
}
2、真实角色
//房东
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要出租房子!!!");
}
}
3、代理角色
public class proxy implements Rent{
private Host host;
public proxy(){
}
public proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
seeHost();
host.rent();
heTong();
fare();
}
//看房
public void seeHost(){
System.out.println("中介带你看房");
}
//收中介费
public void fare(){
System.out.println("收中介费");
}
//签合同
public void heTong(){
System.out.println("签合同");
}
}
4、客户端访问代理角色
public class Client {
public static void main(String[] args) {
//房东要租房子
Host host=new Host();
//代理,中介帮房东租房子,但是呢,代理都会有一些操作!
proxy proxy = new proxy(host);
//你不用面对房东,直接找中介即可
proxy.rent();
}
}
运行结果