Sample Proxy Template


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 will not be loaded from disk



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

Thank you so much!


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;

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


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.



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.


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{

     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 

//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");



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 .



All Articles