Proxy Design Pattern in Java

Proxy is a stand-in object that controls access to the real object. It can delay creation, check permission or add logging.

Real life example

A cheque is a proxy for cash in your bank account.

When to use

The real object is heavy or secret, and you want to load it only when it is really needed (lazy loading).

Complete Java example

Save this as Main.java, then run javac Main.java and java Main.

public class Main {
    public static void main(String[] args) {
        Image img = new ProxyImage("photo.jpg");            // nothing loaded yet
        img.show();                                         // now it loads and shows
    }
}

interface Image { void show(); }

class RealImage implements Image {
    RealImage(String file) { System.out.println("Loading " + file); }   // slow work
    public void show() { System.out.println("Showing image"); }
}

class ProxyImage implements Image {
    private String file;
    private RealImage real;
    ProxyImage(String file) { this.file = file; }
    public void show() {
        if (real == null) real = new RealImage(file);   // load only on first use
        real.show();
    }
}

Output

Loading photo.jpg
Showing image