[Design Pattern] Proxy Pattern 简单案例

Proxy Pattern, 即代理模式,用一个类代表另一个类的功能,用于隐藏、解耦真正提供功能的类,属于结构类的设计模式。

下面是 代理模式的一个简单案例。

Image 定义接口,RealImage, ProxyImage 都实现该接口。RealImage 具有真正显示功能,ProxyImage 作为代表,暴露给客户端使用。

代码实现:

public interface Image {
    
    public void display();
}

RealImage 的实现,提供真正的功能

public class RealImage implements Image {

    private String fileName;
    
    public RealImage(String fileName){
        this.fileName = fileName;
    }
    
    @Override
    public void display() {
        this.loadFromDisk();
        System.out.println("display - " + this.fileName);
    }
    
    public void loadFromDisk(){
        System.out.println("loading [" + this.fileName + "] from disk");
    }
}

ProxyImage ,代表 RealImage 提供对外功能

public class ProxyImage implements Image {

    private String fileName;
    private RealImage realImage;
    
    public ProxyImage(String fileName){
        this.fileName = fileName;
        this.realImage = new RealImage(fileName);
    }
    
    @Override
    public void display() {
        realImage.display();
        System.out.println("proxyImage display " + fileName);
    }
}

演示代理模式,客户端调用代理层,无需了解具体提供功能的底层实现

public class ProxyPatternDemo {

    public static void main(){
        ProxyImage proxyImage = new ProxyImage("aaa.txt");
        proxyImage.display();
    }
}

参考资料

Design Patterns - Proxy Pattern, TutorialsPoint

原文地址:https://www.cnblogs.com/TonyYPZhang/p/5515325.html