首頁  >  文章  >  Java  >  代理人

代理人

Susan Sarandon
Susan Sarandon原創
2024-09-22 22:15:41237瀏覽

代理人

代理是結構設計模式之一,它用於建立代理或占位符對象,用於控制原始物件的存取。
它充當中介,增加額外的控制級別,並且可以在將請求委託給真實物件之前和之後執行額外的操作。

關鍵概念
代理物件:代表真實物件並控制對其的存取。
真實物件(主題):完成工作的實際物件。
Client:與代理人互動的實體,而不是直接與真實物件互動。

讓我們以圖像為例來理解這一點。

//Object interface
public interface Image{
    public void display();
}


//Real object
public class RealImage implements Image {
    private String file;

    public RealImage(String fileName){
        this.file = fileName;
        loadImageFromDisk();
    }
    @Override
    public void display(){
        System.out.println("Rendering image : "+ file);
    }
    private void loadImageFromDisk(){
        System.out.println("Loading image "+file+" from disk");
    }
}

//代理人 class
public class 代理人Image implements Image {
    private Image image;
    private String file;

    public 代理人Image(String fileName){
        this.file =fileName;
    }
    @Override
    public void display(){
        if(image ==null){// create object of RealImage only if the image reference is null, thus resulting in LazyIntialization 
            //( i.e. Initializing the object only when it is needed not beforehand)
            image = new RealImage(file);
        }
        image.display();
    }

}

// client
public class Main {
    public static void main(String args[]){
        Image image = new 代理人Image("wallpaper.png");
        //image is loaded and displayed for the first time
        image.display();
        //image will not be loaded again, only display will be called 
        image.display();
    }
}

輸出:

Loading image wallpaper.png from disk
Rendering image : wallpaper.png

用例
延遲初始化:延遲物件創建,直到絕對必要。
存取控制:根據使用者角色或權限限制對特定方法的存取。
日誌記錄:新增日誌記錄或監控功能。

以上是代理人的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:狀態下一篇:狀態