易学设计模式六 代理模式(Proxy)
代理模式(Proxy)为另一个对象提供一个替身或占位符以控制对这个对象的访问,简而言之就是用一个对象来代表另一个对象。
public abstract class Subject {abstract public void request();}
public class RealSubject extends Subject {public void request() {System.out.println("From real subject");}}
public class ProxySubject extends Subject {private RealSubject realSubject;public ProxySubject() {realSubject = new RealSubject();}public void request() {preRequest();realSubject.request(); //输出一次realSubject.request(); //输出二次postRequest();}public void preRequest() {System.out.print("before request");}public void postRequest() {System.out.println("after request");}}
public class Client {public static void main(String[] args) {Subject subject = new ProxySubject();subject.request();}}