Sample Proxy Template Design-tutorialspoint.com

http://www.tutorialspoint.com/design_pattern/proxy_pattern.htm

Hello,

I am looking to understand the proxy design pattern in java using the example in the link above. In the main method, I don't understand the difference between:

  //image will be loaded from disk

  image.display(); 
  System.out.println("");

  //image will not be loaded from disk

  image.display();  

      

It's a typo? How can the same image.display () methods give different outputs?

Thank you so much!

0


source to share


3 answers


This is not a typo. If you look at the definition ProxyImage

in the tutorial, it certainly has a state:

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();
   }
}

      



When the first call is made, realImage

is NULL and the image will be loaded from disk. After that, the downloaded image is saved in image.realImage

and displayed. On the second call, this image is already cached, and therefore no boot from disk is required.

+3


source


No, this is not a typo.



  • On first call image.display()

    it loads the image from disk. It stores what it downloaded, so ...
  • The second (and subsequent time) you call doesn't need to load the image from disk again.
+1


source


The only difference and an easy way to figure it out is to use the constructor and call the functionality method that should load the image here. If you instantiate your interface with the implementation of this non-proxy MainFunctionalityClass and that implementation loads the image inside that constructor. However, using a proxy is to apply a wrapper over the MainFunctionalityClass, and this time the constructor being called is the name of the proxy, which means there is no MainFunctionalityClass constructor specified here.

    class MainFunctionalityClass implements ICommon{

    MainFunctionalityClass(){
     loadMainFunctionality(); // Costly call
    } 
}

      

So far, the proxy class is defined as:

class Proxy implements ICommon{
 private String var;

Proxy(String var){
this.var = var; //NO call to big functionality, not costly 
}

callMainFunctionality(){
//uses var, MainFunctionalityClass() called
// Costly call but it is called on demand, 
}

class MainClassTest{
 public static void main(String[] args){
 ICommon p = new Proxy("abcd");
p.callMainFunctionality();
}

}

      

Proxy design pattern can be used for

  • Loading large functionality on demand is lazy.
  • Limiting customer transactions (not described above)

To implement this, we need to first use the same interface in both classes and then use the composition in the proxy class .

0


source







All Articles