1、为什么要学代理模式?
因为spring的底层就是这种代理模式。
- 静态代理
- 动态代理
你->中介->房东。
1.1:静态代理
抽象角色:一般使用接口或抽象类来实现
真实角色:被代理的角色(如:房东)
代理角色:代理真实角色的角色(如:中介)
客户:访问代理角色的人。
抽象角色:
public interface Rents {
public void rents();
}
真实角色:
//房东
public class Host implements Rents {
public void rents() {
System.out.println("我要出租房子");
}
}
客户:
public class Client {
public static void main(String[] args) {
Host host = new Host();
Proxy proxy = new Proxy(host);
proxy.rents();
}
}
代理角色:
public class Proxy implements Rents{
private Host host;
public Proxy(Host host) {
this.host = host;
}
public Proxy() {
}
public void rents() {
host.rents();
this.SeeHouse();
}
public void SeeHouse(){
System.out.println("中介带来看很多套房子");
}
}
小结:
- 可以使真实角色的操作更加纯粹,不用去关注一些公共业务。
- 公共代理就是交给代理角色,实现了业务的分工。
- 公共业务发生扩展的时候,方便集中管理