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.
No, it's not a typo.
image.display()
, it loads the image from disk. It stores what it loaded, so... 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
To implement it we need to first to use same interface in both the classes and then to use composition in the proxy class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.