为什么要学习代理模式?因为这就是springAOP的底层!
代理模式的分类:
- 静态代理
- 动态代理
静态代理:
角色分析:
- 抽象对象:一般会使用接口或者抽象类来解决(租房)
- 真实的角色:被代理的角色。(房东)
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属的操作(中介)
- 客户:访问代理对象的人(客户)。
租房:
package com.bernard.demo01;public interface Rent {public void rent();}
房东:
package com.bernard.demo01;public class Host implements Rent{@Overridepublic void rent() {System.out.println("房东要出租房间!");}}
中介:
package com.bernard.demo01;public class Proxy implements Rent{private Host host;public Proxy() {}public Proxy(Host host) {this.host = host;}@Overridepublic void rent() {seeHouse();host.rent();hetong();charge();}public void seeHouse(){System.out.println("看房");}public void hetong(){System.out.println("签合同");}public void charge(){System.out.println("收取中介费");}}
客户:
package com.bernard.demo01;public class Client {public static void main(String[] args) {Host host = new Host();Proxy proxy = new Proxy(host);proxy.rent();}}
