Virtual Proxy
If an object is expensive to instantiate and may not be
needed utilizing a virtual Proxy can hide the fact that
the object does not really exists while allowing the client
to access it.
Imagine books are created and manipulated by an application
but the content may or may not ever be needed.
The interface.
-----------------------------------------------------
public interface IBook{
public String getTitle();
public void setTitle(String title);
public String getContents();
}
-----------------------------------------------------
The Book class.
Imagine this is expensive to create.
Say if it had a contents variable that was initialized
at creatiion time with the entire book contents.
-----------------------------------------------------
class Book implements IBook{
private String title;
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public String getContents(){
//imagine the string returned
//is the entire book contents
return "the book contents";
}
}
-----------------------------------------------------
This is the virtual proxy that will only create a
instance of Book if it is needed to provide content.
-----------------------------------------------------
class BookProxy implements IBook{
private Book book;
private String title;
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public String getContents(){
if(book ==null)
book = new Book();
book.setTitle(this.title);
return book.getContents();
}
}
-----------------------------------------------------
This is the client class.
It is possible for this class to use the book proxy
without suffering the expense of book creation.
This class does indeed retrieve book contents as it
is a test stub for the above classes.
-----------------------------------------------------
class Test{
public static void main(String[] args){
System.out.println("class: Test, method: main");
IBook iBook = new BookProxy();
iBook.setTitle("The Glass Bead Game");
System.out.println(iBook.getContents());
}
}
-----------------------------------------------------
Here is a tar with the above java classes in it.
virtualProxy.tar