代理模式是一種結構型設計模式,它允許通過創建一個代理對象來控制對另一個對象的訪問。
在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.
可以看到,代理對象在訪問真實對象之前和之后可以執行額外的操作,這樣就實現了對真實對象的控制。