Template design pattern in action part1

So finally I got time to complete the blog 🙂

I’ll discuss about how we can solve the problem using templating design pattern. So what we have done, we have written a Template class “CacheTemplate” having a method getCachedData.
getCachedData takes 2 parameters
key: Key for which we have data cached
cacheCallback: If we don’t have data cached then we will call this cacheCallback to get the data and store it into cache.


public class CacheTemplate {
private CacheProvider cacheProvider;
public  T getCachedData(String key,
CacheCallback cacheCallback) {
T data = (T) cacheProvider.get(key);
if (data == null) {
data = cacheCallback.cacheOperation();
cacheProvider.put(key, data);
}
return data;
}
}

Now taking forward the example taken in previos blog, let us apply this template to the “getPersons” method


public List getPersons() {

return cacheTemplate.getCachedData("persons", new CacheCallback>() {
@Override
public List cacheOperation() {
_getPersons();
}
}
}

private List _getPersons() {
persons = //Business logic to get persons;
return persons;
}

Now if you compare the current implementation with the previous implementation and check the concerns we had they all are resolved.
1.) Now our business logic of retrieving the persons is at one place.
2.) Now we have a generic implementation of managing cache.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s