我想你需要的是
Multiton pattern.
The multiton pattern is a design pattern similar to the singleton,
which allows only one
instance of a class to be created. The multiton pattern expands on the
singleton concept to manage a map of named instances as key-value
pairs. Rather than have a single instance per application (e.g. the
java.lang.Runtime object in the Java programming language) the
multiton pattern instead ensures a single instance per key.
public class FooMultiton {
private static final Map instances = new HashMap();
private FooMultiton() {
// no explicit implementation
}
public static synchronized FooMultiton getInstance(Object key) {
// Our "per key" singleton
FooMultiton instance = instances.get(key);
if (instance == null) {
// Lazily create instance
instance = new FooMultiton();
// Add it to map
instances.put(key, instance);
}
return instance;
}
// other fields and methods ...
}
The controllers have common code and since I don’t need to create
multiple instances of these controller, I think they should be
singletons.
您需要单个实例并不一定意味着您需要Singleton模式.您可以拥有一个实例,并在后续调用时传递该实例.不一定使用私有构造函数强制执行单一性.
另请阅读Evil Singletons,了解更多关于单身人士的不足之处.看完之后,如果你仍然觉得你需要Singleton,那就去吧.