
//Subject
abstract class Graphic {
protected String fileName;
abstract void draw();
public String getFileName() {
return fileName;
}
}
//RealSubject
class Image extends Graphic {
public Image(String fileName) {
this.fileName = fileName;
}
//Request()
public void draw() {
System.out.println("draw " + fileName);
}
}
//Proxy
class ImageProxy extends Graphic {
private Image image;
public ImageProxy(String fileName) {
this.fileName = fileName;
}
public void draw() {
getImage().draw();
}
private Image getImage() {
if (image == null) {
image = new Image(fileName);
}
return image;
}
}
//Client
var proxy = new ImageProxy("1.png");
//operation without creating a RealSubject
var fileName = proxy.getFileName();
//forwarded to the RealSubject
proxy.draw();
System.out.println(fileName);
| Provide a surrogate or placeholder for another object to control access to it. The proxy implements the interface of the original object. |