在Java中,代理模式(Proxy Pattern)是一種設計模式,它允許你提供一個代理對象來控制對另一個對象的訪問。代理模式可以在不修改原始類代碼的情況下,增加額外的功能或控制。以下是如何使用代理模式優化代碼結構的幾個步驟:
首先,定義一個接口,該接口將被代理類和客戶端所實現。
public interface Service {
void performAction();
}
創建一個實現該接口的原始服務類。
public class RealService implements Service {
@Override
public void performAction() {
System.out.println("Performing real action.");
}
}
創建一個代理類,該類實現相同的接口,并在內部持有原始服務類的引用。代理類可以在調用原始服務類的方法之前或之后添加額外的邏輯。
public class ProxyService implements Service {
private Service realService;
public ProxyService(Service realService) {
this.realService = realService;
}
@Override
public void performAction() {
System.out.println("Proxy: Preparing to perform action.");
realService.performAction();
System.out.println("Proxy: Action performed.");
}
}
在客戶端代碼中,使用代理類而不是直接使用原始服務類。
public class Client {
public static void main(String[] args) {
Service realService = new RealService();
Service proxyService = new ProxyService(realService);
proxyService.performAction();
}
}
假設我們希望在調用 performAction
方法之前記錄日志,并在方法執行后清理資源。我們可以通過代理類來實現這些功能。
public class ProxyService implements Service {
private Service realService;
private Logger logger;
private ResourceCleaner resourceCleaner;
public ProxyService(Service realService, Logger logger, ResourceCleaner resourceCleaner) {
this.realService = realService;
this.logger = logger;
this.resourceCleaner = resourceCleaner;
}
@Override
public void performAction() {
logger.log("Proxy: Preparing to perform action.");
resourceCleaner.clean();
realService.performAction();
logger.log("Proxy: Action performed.");
resourceCleaner.cleanup();
}
}
public interface Logger {
void log(String message);
}
public interface ResourceCleaner {
void clean();
void cleanup();
}
public class RealLogger implements Logger {
@Override
public void log(String message) {
System.out.println("Real Logger: " + message);
}
}
public class RealResourceCleaner implements ResourceCleaner {
@Override
public void clean() {
System.out.println("Real Resource Cleaner: Cleaning up resources.");
}
@Override
public void cleanup() {
System.out.println("Real Resource Cleaner: Cleanup complete.");
}
}
客戶端代碼保持不變。
public class Client {
public static void main(String[] args) {
Service realService = new RealService();
Logger logger = new RealLogger();
ResourceCleaner resourceCleaner = new RealResourceCleaner();
Service proxyService = new ProxyService(realService, logger, resourceCleaner);
proxyService.performAction();
}
}
通過這種方式,代理模式可以幫助我們集中管理橫切關注點(如日志記錄和資源清理),從而優化代碼結構,提高代碼的可維護性和可擴展性。