Caching with Decorator pattern

Knowledge of software design patterns is a useful tool to have in your tool belt, and one that will come in handy from time to time.  Today I was thinking of ways of applying caching to existing repositories and the one pattern that stood out was the Decorator pattern.  The concept is fairly simple – decorate repositories with a caching implementation.  Most caching follows similar path, let’s say we have a method called “GetProduct(int productId)” here are the steps that it will usually follow:

– See if the product is in cache; if yes then return

– If no; then get it from the database – add it to the cache and return the value

Here is my sample application that decorates EmployeeRepository with a caching implementation.  This does look little bit different than a pure decorator pattern and that’s because I had to take into account how Ninject binding works.

EmployeeCacheDecorator

The IEmployeeCacheDecorator interface simply extends IEmployeeRepository, the reason for that little bit of indirection is so that I can tell ninject to basically give me two implementations of IEmployeeRepository like so

NinjectModule

because I need and instance of EmployeeRepository  to use in my decorator.  Now as you can see, anytime someone calls FindById – I first look in my cache and if it’s not there then I forward the call to my repository, which looks in my database.  The reason that EmployeeCacheDecorator class extends EmployeeRepository rather then getting injected through the constructor is because now I can pick and choose only the methods that I want to apply caching to and leave the other ones untouched.  Here is the class that uses this decorated cache class:

EmployeeBusinessLogic

I think this is a good way of applying caching, logging or any other things that you want to do before or after hitting your database.  It leaves your existing system in place and does not pollute your pure data access code (repositories) with other concerns.  In this case both classes have their own responsibilities, when it’s not in the cache the decorator class delegates the task to the repository and let it deal with the database.  Do I hear Single Responsibility Principal—Smile



One response to “Caching with Decorator pattern”

  1. I suppose this could work for what I am trying to do. I still don’t get the relevance of the IEmployeeCacheDecorator interface, which doesn’t have any members of its own. Why not just use IEmployeeRepository. Anyways thanks!

Leave a comment