Virtual Proxy Pattern

The Virtual Proxy pattern is a memory saving technique that recommends postponing an object creation until it is actually needed.
It is a useful pattern when creating an object is expensive in terms of the memory usage or the processing involved. The object is created the first time it is referenced in the application and the same instance is reused.
The problem with this pattern is that whenever we access the object we need to make sure that it is not null.

See: Proxy

vproxy.jpeg

Note on the example diagram:

  • Proxy has the same interface as the actual object and has a reference to it.
  • Does not need to have interface necessarily.
public class ConcreteProxy implements Proxy {
...
    public void doSomething() {
        ActualObject realObj;
        if (obj == null) realObj = new ActualObject();
        else realObj = obj;
 
        realObj.doSomething();//forward the call to the actual object
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License