想法是创建一个基于'type'返回不同单例实例的工厂类。 [Multiton模式]。另外,单例实例应该被延迟创建。最佳实践:使用延迟初始化的线程安全Multiton模式
下面的代码线程安全吗?使用ConcurrentHashMap使其更简单,但我想尝试使用HashMap。
public class Multiton {
private HashMap<String, Interface> interfaceMap;
private static class Holder {
public static final Multiton INSTANCE = new Multiton();
}
public static Multiton getInstance() {
return Holder.INSTANCE;
}
private Multiton(){
interfaceMap = new HashMap<String, Interface>();
}
public Interface getInterface(String key){
Interface value = interfaceMap.get(key);
if(null == value){
synchronized(interfaceMap){
// double check locking
if(interfaceMap.get(key) == null){
switch(key){
case TypeA : // initialize Type A interface here and put it to map
value = new TypeA();
interfaceMap.put(key, value);
break;
case TypeB : // initialize Type B interface here and put it to map
value = new TypeB();
interfaceMap.put(key, value);
break;
}
}
}
}
return interfaceMap.get(key);
}
}
使用Spring已经为你处理这个。 – 2014-08-27 22:07:53
该应用程序是一个纯Java应用程序。没有春天请愿。 – user170008 2014-08-27 22:08:59
从Spring或其他已经处理此问题的框架修改必要的源代码以解决您的问题。而且,Spring是使用纯Java构建的。 – 2014-08-27 22:09:43