Editorials

Using the Proxy Pattern

Recently I have been enjoying the use of a proxy pattern. A proxy is a software object acting in place of another software object. For example, I was developing a software system for which the SQL database did not yet exist. So I wrote a simple provider that would perform my crud operations, and save them to a disk file. Nothing special about the files. I just didn’t have a database available.

Now I have this disk based persistence…wahoo! I can start writing my application to consume objects. But, what am I going to do when the database persistence is available? I’m going to have to tear all of the disk storage stuff out, and replace it with the database implementation.

This is a problem that may be easily solved with a proxy. The proxy sits between the application and the calls for persistence. All of the application calls for persistence are sent to the proxy. Then, the proxy knows how to call my file system implementation. When the application is modified, all of the persistence pieces may be modified to call the SQL implementation.

If you’re using the Inversion of Control pattern, you can simply use an interface to define the method calls and implement them in both of the file system storage and the database storage. Then all that need happen is that when the proxy is instantiated, the appropriate driver is injected into the proxy. Then it can use either the file system implementation or the database implementation without any code changes. All you are doing is swapping out the driver.

You use the proxy pattern all the time if you think about it. Every time you choose to print a document, you are calling a print routine from your operating system. The operating system provides a proxy into which you can inject the appropriate printer driver implementation for you printer, and the operating system has no knowledge of how it works…just what method calls are implemented. All of the print method calls are passed through the proxy to the printer driver, and out comes a document.

My brother came up with the idea of building a wood router and using a plotter printer driver to operate it. As you can see, if you come up with a device driver that implements the methods defined by the interface, it doesn’t matter if it is generating paper outcome, object outcome (such as print to PDF), or controlling a tool that cuts wood. That’s the value of a proxy. It leaves the physical implementation out of the equation until you want to tie the interface to a specific need.

Tomorrow we’ll talk about using the proxy pattern a little bit more with an implementation that works for SQL databases.

Cheers,

Ben