Proxy Design Pattern

In Proxy pattern, a class represents functionality of another class. 

This type of design pattern comes under structural pattern. 

 

Below is the diagram and code for the example:

We are going to create an Image Interface and concrete classes implementing the Image interface.

ProxyImage is a proxy class to reduce memory footprint of RealImage object loading.

ProxyPatternDemo, our demo class, will use ProxyImage to get an Image object to load and display as it needs.

 

 

Detail code that achieves above diagram.

Step 1. Create the interface Image.java

public interface Image{
       void display();
}

Step 2. Create Concrete class implementing the same interface

public class RealImage implements Image{

   private String FileName;
   public RealImage(String fileName){

     this.FileName = fileName;

      loadFromDisk( fileName )
   }

  public void display(){
    System.out.println("Displaying+ " + FileName)
  }

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

}

ProxyImage.java

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.

ProxyPatternDemo.java

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

      //image will be loaded from disk
      image.display(); 
      System.out.println("");
      
      //image will not be loaded from disk
      image.display();     
   }
}

 

posted @ 2019-07-31 11:09  CodingYM  阅读(187)  评论(0编辑  收藏  举报