I can't get this disentangled.
public class MySingleton<T extends AUsefulClass>{
Map<String, T> myUsefulRegistry;
private static MySingleton<T> _instance = null;
public static instance(){
if(instance == null)
_instance = new MySingleton<T>();
return _instance;
}
}
public class Test{
@Test
public void testThis(){
MySingleton<SomeClass> mySingleton = MySingleton<SomeClass>().instance();
}
}
This parametrization is faulty because you cannot make a static reference to a nonstatic T. Still, I would like to build a parameterizable singleton class.
The problem is that in Java (unlike .NET) you've only got one static variable no matter how many different type arguments you provide - so
MySingleton<Foo>._instanceis equal toMySingleton<Bar>._instance.I suspect you want a
Map<Class<? extends AUsefulClass>, MySingleton>, suppressing the warnings about raw types. Then you'd make yourinstancemethod take aClass<T>parameter as well, so it would know what to look up.Of course, this is assuming you want separate state for different type arguments. If you don't need different state for
MySingleton<Foo>andMySingleton<Bar>you can truly have a single instance, and just cast it while suppressing the unchecked conversion warning.