Do you need to cache your objects?
May 14th, 2008
I’ve found the Cache Management Pattern very useful in more than a couple of projects that needed a simple caching mechanism. Now that we have Generics at our disposal, I think this pattern deserves a tiny change. Something like a generic structure or code that we can follow or use every time we need to cache specific objects.
The Structure
public interface ObjectCacheManager<K, T> {
T fetch(K aKey);
}
public interface ObjectFactory<K, T> {
T make(K aKey);
}
public interface Cache<K, T> {
void add(T anEntry);
T fetch(K aKey);
}
An Example
Note: this is just a toy example… you’ve been warned
Its purpose is to show you the dynamics of this pattern.
public class FooCache implements Cache<String, Foo> {
private final Map<String, Foo> cache;
public FooCache(){
cache = new ConcurrentHashMap<String, Foo>();
}
public void add(Foo entry) {
final String key = entry.getName();
if(cache.get(key) == null){
cache.put(key, entry);
}
}
public Foo fetch(String givenAKey) {
return cache.get(givenAKey);
}
}
public class FooFactory implements ObjectFactory<String, Foo> {
public Foo make(String aKey) {
return new Foo(aKey);
}
}
public class FooCacheManager implements ObjectCacheManager<String, Foo> {
private final ObjectFactory<String, Foo> server;
private final Cache<String, Foo> cache;
public FooCacheManager(){
server = new FooFactory();
cache = new FooCache();
}
public Foo fetch(String aKey) {
Foo foo = cache.fetch(aKey);
if(null == foo){
foo = server.make(aKey);
if(null != foo){
cache.add(foo);
}
}
return foo;
}
}
Let’s get more specific with its use.. shall we?
@Test
public void verifyFooCachingSystem(){
final FooCacheManager manager = new FooCacheManager();
final Foo a = manager.fetch("Superman");
final Foo b = manager.fetch("Superman");
Assert.assertEquals(a, b);
}
And there you go…
Leave a Reply