http://www.tutorialspoint.com/design_pattern/proxy_pattern.htm
Hi,
I am looking to understand proxy design pattern in java using the example in the link above. In 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();
Is this a typo? How can the same 2 image.display() methods give different outputs?
Thanks a lot!
No, it's not a typo.
image.display()
, it loads the image from disk. It stores what it loaded, so...This is not a typo. If you look in the definition of
ProxyImage
in the tutorial, it clearly has state:When the first call is made,
realImage
is null, and the image will be loaded from disk. After that, the loaded image is stored toimage.realImage
and is displayed. At the second call that image is already cached, and hence no load from disk is necessary.The only difference and easy way to understand it is by using constructor and calling the functionality method, which is to load the image here. If you instantiate your interface with the implementation of this non proxy MainFunctionalityClass and that implementation loads the image inside this constructor. However, using proxy is to apply a wrapper over the MainFunctionalityClass and this time, the called constructor is that of the Proxy's, it means, the MainFunctionalityClass constructor is skipped here.
While the proxy class is defined as:
Proxy Design Pattern can be used for
To implement it we need to first to use same interface in both the classes and then to use composition in the proxy class.