Sobes.tech
Junior — Middle

How does the Proxy pattern work and how does it differ from regular objects?

sobes.tech AI

Answer from AI

The Proxy pattern creates a substitute object that controls access to another object, called the real subject. The Proxy can perform additional actions before or after accessing the real object, such as lazy initialization, caching, access control, or logging.

Differences between Proxy and a regular object:

  • Proxy implements the same interface as the real object, so it can be used in place of it.
  • Proxy manages access to the real object, adding additional logic.
  • The client interacts with the Proxy without knowing about the real object.

Example in Java:

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();
    }
}

Here, ProxyImage controls the creation and use of RealImage, loading the image only when necessary.

How does the Proxy pattern work and how does it… - sobes.tech