Multiton pattern


In software engineering, the multiton pattern is a design pattern which generalizes the singleton pattern. Whereas the singleton allows only one instance of a class to be created, the multiton pattern allows for the controlled creation of multiple instances, which it manages through the use of a map.
Rather than having a single instance per application the multiton pattern instead ensures a single instance per key.
Most people and textbooks consider this a singleton pattern. For example, multiton does not explicitly appear in the highly regarded object-oriented programming textbook Design Patterns.

Description

While it may appear that the multiton is a 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, 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 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. However, a multiton is limited to wide use by a single system rather than a myriad of distributed systems.

Drawbacks

This pattern, like the Singleton pattern, makes unit testing far more difficult, as it introduces global state into an application.
With garbage collected languages it may become a source of memory leaks as it introduces global strong references to the objects.

Implementations

In Java, the multiton pattern can be implemented using an enumerated type, with the values of the type corresponding to the instances. In the case of an enumerated type with a single value, this gives the singleton pattern.
In C#, we can also use enums, as the following example shows:
using System.Collections.Generic;
public enum MultitonType ;
public class Multiton