代理模式是一种结构型设计模式,它允许通过创建一个代理对象来控制对另一个对象的访问。
在Java中,可以使用以下步骤来使用代理模式:
public interface Subject {
void request();
}
public class RealSubject implements Subject {
@Override
public void request() {
System.out.println("RealSubject: Handling request.");
}
}
public class ProxySubject implements Subject {
private RealSubject realSubject;
public ProxySubject() {
realSubject = new RealSubject();
}
@Override
public void request() {
System.out.println("ProxySubject: Preparing for request.");
realSubject.request();
System.out.println("ProxySubject: Post-processing after request.");
}
}
public class Client {
public static void main(String[] args) {
Subject subject = new ProxySubject();
subject.request();
}
}
运行客户端代码,输出结果如下:
ProxySubject: Preparing for request.
RealSubject: Handling request.
ProxySubject: Post-processing after request.
可以看到,代理对象在访问真实对象之前和之后可以执行额外的操作,这样就实现了对真实对象的控制。