What is the Proxy pattern and how does it control access to objects?

The Proxy pattern is a structural pattern where a proxy object implements the same interface as a real object and controls access to it, forwarding requests while adding behavior such as lazy loading, access checks, caching, or logging around the real call.

Key Points: • The proxy implements the same interface as the real subject, so it's interchangeable with it from the client's point of view. • A virtual proxy defers creating an expensive object until it's actually needed. • A protection proxy checks permissions before forwarding a request to the real object. • A remote proxy represents an object that lives in a different process or on a different machine. • A logging or caching proxy can record calls or cache results without changing the real object's code.

Example: An ImageProxy can implement the same Image interface as a RealImage, only loading the actual image file from disk the first time display() is called, saving memory for images that are never shown.

Code Example:

interface Image {
    void display();
}

class RealImage implements Image {
    private String filename;
    RealImage(String filename) {
        this.filename = filename;
        loadFromDisk();
    }
    private void loadFromDisk() { System.out.println("Loading " + filename); }
    public void display() { System.out.println("Displaying " + filename); }
}

class ImageProxy implements Image {
    private RealImage realImage;
    private String filename;
    ImageProxy(String filename) { this.filename = filename; }

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

Interview Tip: A concise interview answer is:

"A proxy implements the same interface as the real object and sits in front of it, forwarding calls while adding something extra like lazy loading, access control, or logging. The client can't tell it's talking to a proxy instead of the real object, which is what makes it useful for controlling access without changing the real class."