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() {
host.rent();
seehouse();
fare();
hetong();
}
public void seehouse(){
System.out.println("中介带你看房");
}
public void hetong(){
System.out.println("中介带你签合同");
}
public void fare(){
System.out.println("中介收费");
}
}
4、客户端访问代理角色:我要租房,调用中介,使用接口,访问代理对象
public class Client {
public static void main(String[] args) {
Host host = new Host();
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
-
优点:
1、使真实角色操作更加纯粹,不用去关注公共的业务
2、公共交给代理角色,实现业务的分工
3、公共业务发生拓展时,方便集中管理 -
缺点:一个真实角色产生一个代理角色,代码量会翻倍