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!
This is not a typo. If you look in the definition of ProxyImage
in the tutorial, it clearly has state:
public class ProxyImage implements Image{
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName){
this.fileName = fileName;
}
@Override
public void display() {
if(realImage == null){
realImage = new RealImage(fileName);
}
realImage.display();
}
}
When the first call is made, realImage
is null, and the image will be loaded from disk. After that, the loaded image is stored to image.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.
class MainFunctionalityClass implements ICommon{
MainFunctionalityClass(){
loadMainFunctionality(); // Costly call
}
}
While 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
}
callMainFunctionality(){
//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");
p.callMainFunctionality();
}
}
Proxy Design Pattern can be used for
- Loading big functionality on demand lazily.
- Restricting the operations of the client(not explained above)
To implement it we need to first to use same interface in both the classes and then to use composition in the proxy class.