Proxy Pattern

Proxy is a structural pattern in which a class represents functionality of another class. Proxy pattern implies creating object having original object to interface its functionality to outer world.

In the example there is an Image interface and concrete classes implementing the Image interface. ProxyImage is a proxy class to reduce memory footprint of RealImage object loading. ProxyPatternDemo will use ProxyImage to get an Image object to load and display as it needs.

Proxy Pattern UML Diagram

Step 1 : Create an interface

public interface Image {
void display();
}

Step 2 : Create concrete classes implementing above interface

public class RealImage implements Image {
private String fileName;

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

@Override
public void display() {
System.out.println("Displaying " + fileName);
}

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

public class ProxyImage implements Image {
private RealImage realImage;
private String fileName;

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

@Override
public void display() {
if (realImage == null) {
realImage = new RealImage(fileName);
}

realImage.display();
}
}

Step 3 : Use the ProxyImage to get object of RealImage class when required

public class ProxyPatternDemo {
public static void main(String[] args) {
Image image = new ProxyImage("test_10mb.jpg");

// image will be loaded from the disk
image.display();
System.out.println();

// image will not be loaded from the disk
image.display();
}
}

The output will be :

Loading test_10mb.jpg
Displaying test_10mb.jpg

Displaying test_10mb.jpg

Leave a Reply

Your email address will not be published. Required fields are marked *