Design Patterns - Proxy


// Design Patterns - Structural - Proxy:

In proxy pattern, a class represents functionality of another class. This type 
of design pattern comes under structural pattern.  In proxy pattern, we create 
object having original object to interface its functionality to outer world.

A proxy is a proxy. It acts in place of the real object, but it is not the real 
object, and it forward information to the real object.

A proxy is an object that represents another object. A credit card is a proxy 
for what is in our bank account. Consider a network communication scenario where 
we have a local network and a remote network at a partner site. The program that 
runs at the partner site does not know about our internal representation of the 
data, but we allow the partner to install a piece of our software that runs on 
their network, or we provide a library that expose an interface that the partner 
code can talk to, and that proxy then communicate with our software on our local 
network. A proxy is an object that is acting on the behalf of another object.

We are going to create an Image interface and concrete classes implementing the 
Image interface. ProxyImage is a a proxy class to reduce memory footprint of 
RealImage object loading.

// Step 1: Create an interface.
public interface Image {
   void display();

// Step 2: Create concrete classes implementing the same interface.
public class RealImage implements Image {
   private String fileName;

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

   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;
   public void display() {
      if(realImage == null){
         realImage = new RealImage(fileName);

// Step 3: Use the ProxyImage to get object of RealImage class when required.
Image image = new ProxyImage("test_10mb.jpg");

//image will be loaded from disk

//image will not be loaded from disk
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License