Multiton pattern
From Wikipedia, the free encyclopedia
Multiton is a (disputed) term often used to describe a Singleton-like pattern that allows more than just one instance to be created. While there is no official Gang of Four design pattern called Multiton, there is at least one prominent variation that remains quite useful in software development and is presented here.
The Multiton pattern begins with the concept of the Singleton pattern and expands it into an object pool of keys to objects. Instead of having a single instance per application (e.g. the java.io.Runtime
object in the Java programming language) the Multiton pattern ensures a single instance per key.
An example thread-safe Java implementation follows:
public class FooMultiton { private static final Map instances = new HashMap(); private FooMultiton() // also acceptable: protected, {default} { /* no explicit implementation */ } public static FooMultiton getInstance(Object key) { synchronized (instances) { FooMultiton instance = (FooMultiton) instances.get(key); if (instance == null) { instance = new FooMultiton(); instances.put(key, instance); } return instance; } } public Foo getFoo() { /* implementation not pertinent to pattern */ } public void setFoo(Foo foo) { /* implementation not pertinent to pattern */ } }
[edit] Clarification of Example Code
While it may appear that the Multiton is no more than a simple hash table with synchronized access there are two important distinctions. First, the multiton does not allow clients to add mappings. Secondly, the multiton never returns a null or empty reference; instead, it creates and stores a Multiton instance on the first request with the associated key. Subsequent requests with the same key return the original instance. A hash table is merely an implementation detail and not the only possible approach. The pattern simplifies retrieval of shared objects in an application.
Since the object pool is created only once, being a member associated with the class (instead of the instance), the Multiton retains its flat behavior rather than evolving into a tree structure.
The Multiton is unique in that it provides centralized access to a single directory (i.e. all keys are in the same namespace, per se) of Multitons, where each Multiton instance in the pool may exist having its own state. In this manner, the pattern advocates indexed storage of essential objects for the system (such as would be provided by an LDAP system, for example). However, a Multiton is limited to wide use by a single system rather than a myriad of distributed systems.