Creating a factory that returns singletons
design-patterns, factory, java, singleton
Solution
I think what you need is a 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<Object, FooMultiton> instances = new HashMap<Object, FooMultiton>();
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.
You need single instance does not necessarily mean that you need a Singleton Pattern. You can have a single instance and pass that on subsequent calls to that. Don't necessarily enforce singletonness using `private` constructor.
Also read Evil Singletons for more on down points of Singletons. After reading that if you still feel you need Singleton then go with it.
Problem
I have common code (multiple class that I call controllers) that needs to be shared by multiple packages in the project. I was thinking of creating a factory, that returns these controllers. So, the factory would have a hashmap, that can return the controller asked for or create a new one if not created. The controllers have common code and since I don't need to create multiple instances of these controller, I think they should be singletons. Does this seem like a good approach?