I have been reading on Design Patterns recently, and there's something I don't understand about the Proxy Pattern.
quote from the book:
- 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?
Aucun commentaire:
Enregistrer un commentaire