As I started dealing with NHibernate and other OS projects in the .net world, I wondered how
often the use of proxies where mentioned. So I started out reading a bit around and in the end it
becomes clear. I think everybody has used the pattern behind it sometimes, even if one didn’t
know about it. The following example shows the principle usage of the proxy pattern and what
it is good for.
“…A proxy, in its most general form, is a class functioning as an interface to something else…”
In practice this short definition means, a proxy encloses a real object in its entirety but presents
the same signature to the client. So a client must not know if he works with the proxy or
the real object. This is very usefull in a lot of cases, since you build an interface to a class and
can extend the functionallity and behaviour of it, without changing it’s original implementation.
The example above shows an proxy that implements the ITask interface and delegates all calls
to one of the interfaces methods to an internal instance of a TaskImpl - object.
Ok, the proxy hides the real implementation, but furthermore it does nothing real useful. If we start
a task, it is simply executed. But what about for instance permissions and dependencies? Not every
user can execute every task, I think this is common for every application. So where can we validate
if the user is allowed to execute a specific task? The TaskImpl is not a good place for this I think,
since there only the execution logic should be implemented. I would prefer implementing this in the
proxy. Since every ITask - object is created by a factory, it is easy to interfere the process of creating
an ITask instance and put the proxy on job.
We use a simple User class to emulate the permission validation:
The TaskImpl stays untouched, but the proxy implementation of doExecute now looks like this:
The task will be only executed, if the User has the permission to do this. Instead of throwing an
exception it also could simply return false.
Now we can run two simple tests with it:
As we can see, all test are successful:
So finally this simple example shows, what problems can be solved using proxies. As we can see,
the client stays completly untouched and the TaskImpl too.
But thinking of real world applications, interfaces and classes are useally complex an have lots of
properties and methods. It would be worse to code proxies for it by hand. In the end there is no need
to do this, because there a libraries out there, doing the job very good. But thats for the next part…