代理模式--设计模式
为什么要学习代理模式?
因为这是SpringAOP的底层!
1、定义:
在不改变源码的情况下,实现对目标对象的功能扩展
根据代理类的生成时间不同可以将代理分为静态代理和动态代理两种
静态代理
角色分析
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色, 代理真实角色后,我们一般会做一些附属操作
- 客户:访问代理对象的人
代码步骤:
1、接口
//租房
public interface Rent {void rent();
}
2、真实角色
public class Host implements Rent{@Overridepublic void rent() {System.out.println("房东出租房子");}
}
3、代理角色
public class Proxy implements Rent {private Host host;public Proxy() {}public Proxy(Host host) {this.host = host;}@Overridepublic void rent() {host.rent();seeHouse();sendHouse();}//看房public void seeHouse() {System.out.println("中介带看房");}//租房public void sendHouse() {System.out.println("我租房子");}
}
4、客户端访问代理角色
public class Client {public static void main(String[] args) {Host host = new Host();//代理Proxy proxy = new Proxy(host);proxy.rent();}
}
输出结果:
房东出租房子
中介带看房
我租房子
代理模式的好处
可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
公共业务交给代理角色!实现了业务的分工
公共业务发生扩展的时候,方便集中管理