Skip to content

代理模式

意图

为其他对象提供一种代理以控制对这个对象的访问:延迟加载、权限校验、远程调用、日志等。

类图

Java 示例(静态代理)

java
public interface Image {
    void display();
}

public class RealImage implements Image {
    private final String file;
    public RealImage(String file) {
        this.file = file;
        loadFromDisk();
    }
    private void loadFromDisk() { System.out.println("load " + file); }
    public void display() { System.out.println("display " + file); }
}

public class ProxyImage implements Image {
    private final String file;
    private RealImage real;
    public ProxyImage(String file) { this.file = file; }
    public void display() {
        if (real == null) real = new RealImage(file);
        real.display();
    }
}

JDK 动态代理Proxy.newProxyInstance + InvocationHandlerCGLIB 通过子类生成代理,Spring AOP 常用。

进入第四篇:责任链模式