Design Pattern: Proxy

A proxy is a stand-in for something or someone else. As an actor, you might hire a proxy to attend an autograph signing session. Your proxy is providing a layer between you and your fans, but can forward relevant messages as necessary. You want your proxy to behave as much like you do as possible, so that the fans believe they are interacting with you directly.

Proxies in software are similar to proxies in real life. You might create a distributed object proxy. Such a proxy is designed to make its clients think that they are directly interacting with the object, when in reality the object lives in a process on a remote machine. The proxy manages the intricacies of communicating with the distributed object while ensuring that the client remains blissfully ignorant of these details.

As you might imagine, proxies in Java are heavily dependent upon having both the proxy and the target class—the class that the proxy is "standing in" for—implement a common interface. The proxy needs to respond to all the same messages as the target, and forward them as appropriate.

In this article, I'll demonstrate use of a proxy that provides a security layer, disallowing clients with insufficient access from executing specific methods.

I've built a Portfolio class using test-driven development (TDD). The simple implementation of Portfolio provides two query methods, numberOfHoldings and sharesOf, and one update method named purchase.

The InvalidSymbolException class is simply an empty subclass of RuntimeException.

The first step toward building a proxy is to define a common interface. I execute an Extract Implementer refactoring [Feathers2004], ending up with an interface named Portfolio and an implementation of the Portfolio interface named PortfolioImpl.