在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();
}
}
通过这种方式,代理模式可以帮助我们集中管理横切关注点(如日志记录和资源清理),从而优化代码结构,提高代码的可维护性和可扩展性。