代理人

代理是结构设计模式之一,它用于创建代理或占位符对象,用于控制原始对象的访问。
它充当中介,增加额外的控制级别,并且可以在将请求委托给真实对象之前和之后执行额外的操作。

关键概念
代理对象:代表真实对象并控制对其的访问。
真实对象(主题):完成工作的实际对象。
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 disp

lay(){ system.out.println("rendering image : "+ file); } private void loadimagefromdisk(){ system.out.println("loading image "+file+" from disk"); } } //proxy class public class proxyimage implements image { private image image; private string file; public proxyimage(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 proxyimage("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

用例
延迟初始化:延迟对象创建,直到绝对必要时。
访问控制:根据用户角色或权限限制对特定方法的访问。
日志记录:添加日志记录或监控功能。