The proxy pattern

I recently had to prepare a four minutes talk to present my favourite design pattern. Proxy was my choice and it made me realise a few things about it.

First that in the pattern (as it was defined by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides) the proxy has the same responsibilities as the real subject. This is a much more restrictive definition than what I had come to think as proxies. Also in one form or another the proxy is used to control (mediate ?) access to the real subject. Nothing new here, this is the plain definition.

I have three typical uses for the Proxy. First the access to remote objects which is now so commonplace that people hardly notice it. Second error handling around resources that can become unavailable (connections for instance). Finally access to pooled or cached instances of objects. In that last case it means the proxy can be left as a permanent placeholder and negotiate the use of the actual resource when needed (see of the impact of caching on your design). This last use also realises for dynamic objects what the flyweight pattern intends for static ones.

After thinking about I found why this pattern was significant for me. First is that proxies enable some degree of separation of concerns (say error handling versus and actual function), making the proxy a lightweight aspectisation (see how Spring does aop). Second I like it because it provides a great example of the usefulness of loose coupling through interfaces (another one being unit testing). Finally I find that proxies give a more dynamic feel to an application. They enable easy reconfiguration, hot swapping of objects and controls. This is particularly useful in a language like Java.

I will end this short presentation of my “favourite design pattern” with a note on dynamic proxies in Java. They do not necessarily lead to implementations of the proxy pattern. They can just as well be used to implement other structural patterns (from facade to bridge and adapter).

And that made me realise that design patterns are first and foremost about the intent. The implementation of different patterns can be the same, making them difficult to identify in a code base. One more reason to use sensible naming in your code I guess.

Post to Twitter

Leave a Reply