代理模式之静态代理
代理模式
为什么要学习代理模式:代理模式是SpringAOP的底层
分类:动态代理和静态代理
你和中介都实现了找房子的接口,但是中介找房子的功能比你强,所以你将找房子的需求交给了中介来做
静态代理
角色分析:
- 抽象角色:一般使用接口和抽象类来解决
- 真实角色(房东):被代理的角色
- 代理角色(中介):代理真实角色,代理真实角色后,我们一般会做一些附属操作
- 客户(租房的人):访问代理对象的人
还不理解?上代码!
1.抽象角色(接口)
public interface Host {
public void rent();
}
2.真实角色(房东)
public class HostMaster implements Host{
public void rent() {
System.out.println("房东要出租房子");
}
}
3.代理角色(中介)
public class Proxy {
public Host host;
public Proxy() {
}
public Proxy(Host host) {
super();
this.host = host;
}
public void rent() {
seeHouse();
host.rent();
fee();
sign();
}
//看房
public void seeHouse() {
System.out.println("看房子");
}
//收费
public void fee() {
System.out.println("收中介费");
}
//合同
public void sign() {
System.out.println("签合同");
}
}
4.客户访问代理角色
import com.xy.pojo.Host;
import com.xy.pojo.HostMaster;
import com.xy.pojo.Proxy;
public class client {
public static void main(String[] args) {
//房东要出租房子
Host host = new HostMaster();
//中介帮房东出租房子,但也收取一定费用(增加一些房东不做的操作)
Proxy proxy = new Proxy(host);
//看不到房东,但通过代理,还是租到了房子
proxy.rent();
}
}