简介:
代理类跟被代理类都实现同一个接口,在代理类中调用被代理类的接口方法来完成具体的工作,同时添加一些额外的处理逻辑。客户端调用代理对象而不是直接调用被代理对象。
类图:
示例代码:
代理类跟被代理类都需实现的接口
1 public interface Subject {2 public void doSomething();3 }
真正的实现类:
1 public class RealSubject implements Subject{2 3 @Override4 public void doSomething() {5 System.out.println("I am doing the real thing"); 6 }7 8 }
代理类:
1 public class Proxy implements Subject{ 2 3 private RealSubject realSubject=new RealSubject(); 4 5 @Override 6 public void doSomething() { 7 realSubject.doSomething(); 8 System.out.println("I am doing the extra thing"); 9 }10 11 }
客户端:
1 public class Client {2 3 public static void main(String args[]) {4 Subject subject = new Proxy();5 subject.doSomething();6 }7 }
运行结果:
I am doing the real thingI am doing the extra thing