在Java中,代理模式是一種設計模式,它允許你提供一個代理對象來控制對另一個對象的訪問。這種模式有許多優點,如延遲加載、日志記錄、安全檢查等。以下是一些Java代理模式的最佳實踐:
以下是一個簡單的靜態代理示例:
// 目標接口
public interface Service {
void doSomething();
}
// 目標實現類
public class RealService implements Service {
@Override
public void doSomething() {
System.out.println("Doing real work...");
}
}
// 代理類
public class ServiceProxy implements Service {
private Service realService;
public ServiceProxy(Service realService) {
this.realService = realService;
}
@Override
public void doSomething() {
System.out.println("Before method call...");
realService.doSomething();
System.out.println("After method call...");
}
}
// 客戶端代碼
public class Client {
public static void main(String[] args) {
Service realService = new RealService();
Service proxy = new ServiceProxy(realService);
proxy.doSomething();
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
// 目標接口
public interface Service {
void doSomething();
}
// 目標實現類
public class RealService implements Service {
@Override
public void doSomething() {
System.out.println("Doing real work...");
}
}
// 動態代理處理器
class ServiceInvocationHandler implements InvocationHandler {
private Object target;
public ServiceInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method call...");
Object result = method.invoke(target, args);
System.out.println("After method call...");
return result;
}
}
// 客戶端代碼
public class Client {
public static void main(String[] args) {
Service realService = new RealService();
Service proxy = (Service) Proxy.newProxyInstance(
realService.getClass().getClassLoader(),
realService.getClass().getInterfaces(),
new ServiceInvocationHandler(realService)
);
proxy.doSomething();
}
}
通過遵循這些最佳實踐,你可以更有效地使用Java代理模式,提高代碼的可維護性和可擴展性。