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…

patterns, programming | Comments | Trackback

Leave a Reply

  1.  
  2.  
  3.  
  4. XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
  5. Spam Protection by WP-SpamFree

You can keep track of new comments to this post with the comments feed.

 

May 2008
M T W T F S S
« Apr   Jun »
 1234
567891011
12131415161718
19202122232425
262728293031  

Categories

Archives

Tags