Search code examples
javagenericsfactory-pattern

Java generic container factory


I want to make a factory for cache containers, something like

public interface CacheMapFactory {
    public Map<K,V> createCacheMap(String tag, Class<K> kClass, Class<V> vClass);
}

with a possible simple implementation for testing

public class InMemoryCacheMapFactory implements CacheMapFactory {
    public Map<K,V> createCacheMap(String tag, Class<K> kClass, Class<V> vClass) {
        return new HashMap<K,V>();
    }
}

Other implementations might be, for example, based on Memcached or some other key-value storage.

Is it possible to convert the pseudocode above into something compileable with the desired semantics?


Solution

  • Your code would compile if you add another <K,V> to the methods:

    public interface CacheMapFactory {
      public <K,V> Map<K,V> createCacheMap(String tag, Class<K> kClass, Class<V> vClass);
    }
    
    public class InMemoryCacheMapFactory implements CacheMapFactory {
      public <K,V> Map<K,V> createCacheMap(String tag, Class<K> kClass, Class<V> vClass) {
        return new HashMap<K,V>();
      }
    }
    

    I'm not sure what the tag would do, but I guess that's part of the further implementation.

    Additionally, you could rely on type inference like this:

    public interface CacheMapFactory {
      public <K,V> Map<K,V> createCacheMap(String tag );
    }
    
    public class InMemoryCacheMapFactory implements CacheMapFactory {
      public <K,V> Map<K,V> createCacheMap(String tag ) {
        return new HashMap<K,V>();
      }
    }
    
    public class Test {
      public void test() {
        CacheMapFactory f = new InMemoryCacheMapFactory();
        Map<String, Long> m = f.createCacheMap( "mytag" ); //K and V are inferred from the assignment
      }
    }