天天看點

[Design Pattern] Proxy Pattern 簡單案例

Proxy Pattern, 即代理模式,用一個類代表另一個類的功能,用于隐藏、解耦真正提供功能的類,屬于結構類的設計模式。

下面是 代理模式的一個簡單案例。

Image 定義接口,RealImage, ProxyImage 都實作該接口。RealImage 具有真正顯示功能,ProxyImage 作為代表,暴露給用戶端使用。

[Design Pattern] Proxy Pattern 簡單案例

代碼實作:

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

繼續閱讀