15.01.2013 Views

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9 - Back to Basics: Proxy This and Proxy That<br />

Proxy Domain Pattern<br />

A proxy is something acting as something else. In legal terms, a proxy is someone given authority to vote<br />

or act on behalf <strong>of</strong> someone else. Such a proxy has the same rights and behaves pretty much li ke the<br />

person being proxied. In the hardware world, a proxy server sits between you and a server you're<br />

accessing. The proxy server transparently behaves just like the actual server, but with additional<br />

functionality - be it caching, logging or filtering. In s<strong>of</strong>tware, the proxy design pattern is a class that<br />

behaves like another class. For example, if we were building a task tracking system, we might decide to<br />

use a proxy to transparently apply authorization on top <strong>of</strong> a task object:<br />

public class Task<br />

{<br />

public static Task FindById(int id)<br />

{<br />

return TaskRepository.Create().FindById(id);<br />

}<br />

public virtual void Delete()<br />

{<br />

TaskRepository.Create().Delete(this);<br />

}<br />

}<br />

public class TaskProxy : Task<br />

{<br />

public override void Delete()<br />

{<br />

if (User.Current.CanDeleteTask())<br />

{<br />

base.Delete();<br />

}<br />

else<br />

{<br />

throw new PermissionException(...);<br />

}<br />

}<br />

}<br />

Thanks to polymorphism, FindById can return either a Task or a TaskProxy. The calling client<br />

doesn't have to know which was returned - it doesn't even have to know that a TaskProxy exists. It just<br />

programs against the Task's public API.<br />

Since a proxy is just a subclass that implements additional behavior, you might be wondering if a Dog is<br />

a proxy to a Pet. Proxies tend to implement more technical system functions (logging, caching,<br />

authorization, remoting, etc) in a transparent way. In other words, you wouldn't declare a variable as<br />

TaskProxy - but you'd likely declare a Dog variable. Because <strong>of</strong> this, a proxy wouldn't add members<br />

(since you aren't programming against its API), whereas a Dog might add a Bark method.<br />

<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />

74

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!