2

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?

du369
  • 821
  • 8
  • 22

1 Answers1

1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • What if there are multiple expensive procedures in the `RealClass`, and each of them is needed by different methods? How to deal with that with the `Proxy Pattern`? Won't it be less effective because the `ProxyClass`'s `create on demand` would actually call some expensive but unnecessary procedures? – du369 Feb 21 '16 at 02:22
  • @du369 Proxy is not about dealing with slow object construction. Expensive constructors are only one specific case where proxy is helpful, but mostly the idea of a proxy is to hide some particulars about an object behind an interface. When you have multiple expensive methods, you might as well let the first caller of the method bear the expense of calling them, and cache the result after. – Sergey Kalinichenko Feb 21 '16 at 03:18