在Java中實現代理模式有兩種常見的方式:靜態代理和動態代理。
// 接口
interface Image {
void display();
}
// 被代理類
class RealImage implements Image {
private String fileName;
public RealImage(String fileName) {
this.fileName = fileName;
loadFromDisk();
}
private void loadFromDisk() {
System.out.println("Loading image from disk: " + fileName);
}
public void display() {
System.out.println("Displaying image: " + fileName);
}
}
// 代理類
class ProxyImage implements Image {
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName) {
this.fileName = fileName;
}
public void display() {
if (realImage == null) {
realImage = new RealImage(fileName);
}
realImage.display();
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Image image = new ProxyImage("test.jpg");
image.display();
}
}
java.lang.reflect.Proxy
類和java.lang.reflect.InvocationHandler
接口來實現。以下是一個簡單的動態代理示例:import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
// 接口
interface Image {
void display();
}
// 被代理類
class RealImage implements Image {
private String fileName;
public RealImage(String fileName) {
this.fileName = fileName;
loadFromDisk();
}
private void loadFromDisk() {
System.out.println("Loading image from disk: " + fileName);
}
public void display() {
System.out.println("Displaying image: " + fileName);
}
}
// InvocationHandler實現
class ImageInvocationHandler implements InvocationHandler {
private Image image;
public ImageInvocationHandler(Image image) {
this.image = image;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method " + method.getName());
Object result = method.invoke(image, args);
System.out.println("After method " + method.getName());
return result;
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Image realImage = new RealImage("test.jpg");
Image dynamicProxy = (Image) Proxy.newProxyInstance(
realImage.getClass().getClassLoader(),
realImage.getClass().getInterfaces(),
new ImageInvocationHandler(realImage));
dynamicProxy.display();
}
}
無論是靜態代理還是動態代理,代理類都可以在被代理類的方法前后加入額外的邏輯,實現對被代理類的控制和增強。動態代理相對于靜態代理的優勢在于可以簡化代理類的編寫,同時一個代理類可以代理多個接口。