
代理是用于创建代理或占位符对象,控制原始对象访问的结构设计模式之一。 作为中介,可以提高额外的控制水平,并且可以在将请求委托给真实对象之前和之后进行额外的操作。
关键概念:代理对象:代表真实对象,控制其访问。真实对象(主题):完成工作的实际对象。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");
}
}
//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
用例:延迟初始化:在绝对必要之前,创建延迟对象。访问控制:访问特定的方法是根据用户的角色或权限进行的。日志记录:添加日志记录或监控功能。
以上是代理的详细内容,请关注图灵教育的其他相关文章!