The Proxy pattern is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object, e.g. check access permissions, log the requests, cache the request results, etc.
定义接口
java
public interface Subject {
void request();
}
创建真实对象
java
public class RealSubject implements Subject {
@Override
public void request() {
System.out.println("RealSubject: Handling request.");
}
}
创建代理对象
java
public class Proxy implements Subject {
private RealSubject realSubject;
@Override
public void request() {
if (realSubject == null) {
realSubject = new RealSubject();
}
System.out.println("Proxy request");
realSubject.request();
}
}
使用代理对象
java
public class ProxyPatternDemo {
public static void main(String[] args) {
Subject proxy = new Proxy();
proxy.request();
}
}