Proxy Pattern Demo

Demo Code

package ProxyPatternDemo; interface Image { void display(); }
package ProxyPatternDemo; 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); } realImage.display(); } }
package ProxyPatternDemo; 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); } }

Driver:

In this example, ProxyImage is a proxy class that controls the access to RealImage. The image is loaded from the disk only when the display() method is called for the first time. For subsequent calls to the display() method, the loaded image from the first call is used, saving disk read operations. This is an example of a Virtual Proxy, where a heavy object (an image file on disk in this case) is not loaded until it's needed, and subsequent requests use the cached data.