代理模式
当无法直接访问某个对象或访问某个对象存在困难时可以通过一个代理对象来间接访问,为了保证客户端使用的透明性,所访问的真实对象与代理对象需要实现相同的接口:
UML
Java
- 定义接口Sourceable:
public interface Sourceable { void method(); }
- Source实现Sourceable作为被代理的类:
public class Source implements Sourceable { public void method() { System.out.println("the original method!"); } }
- 代理类Proxy注入Source实例,来实现Sourceable接口,作为代理类
public class Proxy implements Sourceable { private Source source; public Proxy() { super(); this.source = new Source(); } public void method() { before(); source.method(); atfer(); } private void atfer() { System.out.println("after proxy!"); } private void before() { System.out.println("before proxy!"); } }
- 测试类:
public class ProxyTest { public static void main(String[] args) { Sourceable source = new Proxy(); source.method(); } }
- 测试结果:
before proxy! the original method! after proxy!