Tuesday, April 29, 2008

Design Patterns – Template method

The idea is to design a method in a superclass that defines the skeleton of an algorithm. Implementation of varying steps in the algorithm is deferred to a subclass. The superclass can implement a default.

An example would be to create a mechanism for caching objects. The logic for how to cache objects remains the same so we create a template method for it. However, the means for how to get the object from storage differs so it is left to the subclass to implement. The logic is something like:

if (IsObjectInCache(anObjectKey))
{
return GetObjectFromCache(anObjectKey);
}
else
{
Object anObject = GetObjectFromStorage(anObjectKey);
SaveObjectInCache(anObjectKey, anObject);
}


The SaveObjectInCache is then overridden in the subclass.

However, for this example this pattern might not be ideal for this situation. Since caching is normally an application wide concern it might be better solved using an AOP technique or somehow implementing it more loosely using in combination with the Decorator pattern.

Another possible approach would be this: Have all business entities implement a single interface that takes their key (in form a Dictionary object created automatically by using reflection) and loads the object representation. Then have a CacheManager implementing the method skeleton.

So remember that the drivers behind this pattern can be created using some other technique than subclassing.

No comments: