We continue a look at the structural patterns with a look at the proxy. This is much like the flyweight we reviewed in the last episode. However, it has a different focus. The flyweight can be used to implement a form of proxy but is a solution to a large number of instances where this is a different goal.
The Proxy Pattern Defined
As always, we will start with the “Gang of Four” intent to set the stage for our discussion.
That, once again, provides a short and simple description of our pattern. The proxy saves us from having to instantiate an object before we start using it. The proxy acts like a class as needed, but it passes communication back and forth between the caller and the object. This approach provides us with ways to access an instance remotely or without moving around the full instance.
Applying The Pattern
The implementation is a class that implements key interfaces and has core attributes of the one it works with. There might be pointers and references to more complete values or implementations hidden under the covers. With this pattern, we do not need to worry the user about those details. The caller will see this as the same as the primary class. We can even fully retrieve values as needed in a just-in-time manner. Thus, a proxy allows us to minimize memory footprints while providing complete functionality.
Java, PHP, C#, etc.
Once again, a proxy is a class. There might be a case where it and a parent class alone would be useful. However, you typically will find that there is an interface or maybe interfaces involved as well. These facts make the implementation the same across object-oriented languages and nothing special is needed whether you use C#, Java, PHP, or something else.