Search code examples
javaoopdesign-patternsproxy-pattern

Why bother using the proxy pattern when we can defer the expensive procedures in the RealClass?


I have been reading on Design Patterns recently, and there's something I don't understand about the Proxy Pattern.

quote from the book:

  1. A virtual proxy creates expensive objects on demand. The ImageProxy described in the Motivation is an example of such a proxy.

I get it that this pattern can be used to create expensive objects on demand. And this example also illustrates the usage quite well.

Below is the constructor of the proxied class RealImage. Method loadFromDisk() denotes the expensive procedure.

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

And the proxy class ProxyImage in the example does just what it is intended to do: to create expensive objects on demand.

But my question is: why can't we just remove the expensive loadFromDisk() method from the constructor and put it somewhere it is absolutely needed,

like here?

  public void display() {
      if(!loaded){
          loadFromDisk(fileName);
          loaded = true;
      }
      //then display
   }

So why bother using a proxy at all?


Solution

  • The problem the proxy pattern solves in this situation is code duplication. Imagine a situation where you have dozens of method similar to display() where loaded flag needs to be checked. Your code would look like this:

    public void display() {
        if(!loaded){
            loadFromDisk(fileName);
            loaded = true;
        }
        //then display
    }
    public void resize(double scale) {
        if(!loaded){
            loadFromDisk(fileName);
            loaded = true;
        }
        //then resize
    }
    ... // more methods go here
    public void save() {
        if(!loaded){
            loadFromDisk(fileName);
            loaded = true;
        }
        //then save
    }
    

    Even if you put the if(!loaded){... code into a method and call it from all methods, you need to remember to perform the call. This is error prone, and may cause problems down the road, especially for new programmers coming into the project.