Sobes.tech
Junior — Middle

How does the Proxy pattern act as an intermediary for the original object?

sobes.tech AI

Answer from AI

The Proxy pattern in Java acts as an intermediary between the client and the original object. The Proxy controls access to this object, can add additional logic before or after calling the original methods, such as caching, access rights verification, lazy initialization, or logging.

Thus, the client interacts with the Proxy just like with the original object, but the Proxy manages the calls and can alter behavior without changing the original object itself.

Example:

interface Image {
    void display();
}

class RealImage implements Image {
    private String filename;

    public RealImage(String filename) {
        this.filename = filename;
        loadFromDisk();
    }

    private void loadFromDisk() {
        System.out.println("Loading " + filename);
    }

    public void display() {
        System.out.println("Displaying " + filename);
    }
}

class ProxyImage implements Image {
    private RealImage realImage;
    private String filename;

    public ProxyImage(String filename) {
        this.filename = filename;
    }

    public void display() {
        if (realImage == null) {
            realImage = new RealImage(filename); // lazy creation
        }
        realImage.display();
    }
}

// Usage:
Image image = new ProxyImage("photo.jpg");
image.display(); // loads and displays
image.display(); // only displays, no reloading

In this example, the Proxy controls the creation and access to the real object, optimizing resource management.

How does the Proxy pattern act as an intermediary for… - sobes.tech