A Few Words About The Decorator Pattern

time to read 6 min | 1117 words

I was asked about my recent post about Generic Repositores, the question was what is the place of the Security Decorator?

The Decorator Pattern is one of my favorites with regard to building flexible APIs. For the purpose of the discusion, I am going to concentrate on just the Get(id) method:

public class SecurityReposiotyDecorator<T> : IRepository<T>

{

    IRepository<T> inner;

    public SecurityReposiotyDecorator(IRepository<T> inner)

    {

        this.inner = inner;

    }

    public T Get(int id)

    {

        Security.AssertCanRead(typeof(T), id, User.Current);

        return inner.Get(id);

    }

   ...

}

As you can see, the security decorator makes a check for the validity of the current request, and pass it on if it is valid (other wise it throws). This is a really nice way to dress a component with new behaviors. The common usage is something like:

IRepository<Customer> securedRepository =
   new SecurityReposiotyDecorator<Customer>(
new NHibernateRepository<Customer>());

Customer cust = securedRepository.Get(15);

Usually, you will not create the full chain in place (I usually have at least Logging, Transactional, Security and Caching decorators), but use a factory or an Invertion Of Control container to build the chain. This way, you can ask for SecuredTransactionalWithoutLogginReposioty<Customer>, and it a work of a moment to create it.

Next time, how to use an Inversion Of Control Container to get some really cool results out of this pattern.