The Proxy Design Pattern is a structural design pattern that provides a surrogate or placeholder for another object to control access to it. This pattern is useful when you want to add an extra layer of control over access to an object. The proxy acts as an intermediary, controlling access to the real object.
The Proxy:
Acts as a surrogate or placeholder for the RealSubject. It controls access to the real object and may provide additional functionality such as lazy loading, access control, or logging.
Implements the same interface as the RealSubject (Subject).
Subject (Image Interface): The Image interface declares the common methods for displaying images, acting as a blueprint for both the real and proxy objects. In this design, it defines the display() method that both RealImage and ProxyImage must implement. This ensures a uniform interface for clients interacting with image objects.
// Subject
interface Image {
void display();
}
RealSubject (RealImage Class): The RealImage class represents the real object that the proxy will control access to.
// RealSubject
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadImageFromDisk();
}
private void loadImageFromDisk() {
System.out.println("Loading image: " + filename);
}
public void display() {
System.out.println("Displaying image: " + filename);
}
}
Proxy (ProxyImage Class): The ProxyImage class acts as a surrogate for the RealImage. It also implements the Image interface, maintaining a reference to the real image object.
// Proxy
class ProxyImage implements Image {
private Image realImage;
private String filename;
public ProxyImage(String filename) {
this.filename = filename;
}
public void display() {
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}
// Client code
public class ProxyPatternExample {
public static void main(String[] args) {
Image image = new ProxyImage("example.jpg");
// Image will be loaded from disk only when display() is called
image.display();
// Image will not be loaded again, as it has been cached in the Proxy
image.display();
}
}