代理模式是对象的结构模式。代理模式给某一个对象提供一个代理对象,并有代理对象控制对原对象的 引用。
一、类图
二、示例
1、结构图
2、java代码
Subject抽象类:
package proxy;
abstract public class Subject {
abstract public void request();
}
RealSubject类:
package proxy;
public class RealSubject extends Subject{
public void request() {
System.out.println("Request from realSubject......");
}
}
ProxySubject类:
package proxy;
public class ProxySubject extends Subject {
private RealSubject realRubject;
public void request() {
preRequest();
if(realRubject==null){
realRubject = new RealSubject();
}
realRubject.request();
postRequest();
}
private void postRequest() {
System.out.println("PostRequest from proxySubject......");
}
private void preRequest() {
System.out.println("PreRequest from proxySubject......");
}
}
Client类:
package proxy;
public class Client {
public static void main(String args[]){
Subject subject = new ProxySubject();
subject.request();
}
}