BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 2.0+

Multiton Design Pattern

The Multiton design pattern is an extension of the singleton pattern. It ensures that a limited number of instances of a class can exist by specifying a key for each instance and allowing only a single object to be created for each of those keys.

What is the Multiton Pattern?

In a previous article I described the singleton design pattern, a Gang of Four design pattern that restricts the instantiation of a class. When an object of the type is first requested, using a static method, an instance is created and returned. Subsequent requests return the same object reference. This is ideal when you need an object that connects to a resource that only supports one connection. For example, you may have a security camera that requires a controller object but where only one controller may be linked to the camera.

The multiton design pattern is very similar to the singleton. When a request is made for an object, a key is passed to a static method that will generate or return one. If the key has not been used before, a new object is instantiated, linked to the key and returned. If the key has been used before, the object previously linked to that key is returned. Essentially, the multiton provides the functionality of a group of singletons.

If we consider the security camera example mentioned above, a multiton would be useful when several cameras must be controlled, each with a linked controller class. Each controller would be represented by a single key in the multiton. This means that you could request a controller using a specified camera key to obtain the correct object for that camera. There would never be a situation where two or more controllers were linked to the same camera.

Implementing the Multiton Pattern

Multiton Design Pattern UML

The UML class diagram above describes an implementation of the multiton design pattern. In the diagram there is a single class. The only public member of the class is the GetMultiton method. This returns one of the instances held in the private "instances" dictionary, creating the instance first if the specified key is unknown.

The constructor for the multiton is made private to prevent other code from creating instances that would not be held in the dictionary. The class is also sealed to prevent subclassing that could break the multiton rules.

The following code shows the basic code of the design pattern implemented using C#:

public sealed class Multiton
{
    static Dictionary<string, Multiton> _instances = new Dictionary<string, Multiton>();
    static object _lock = new object();

    private Multiton() { }

    public static Multiton GetMultiton(string key)
    {
        lock (_lock)
        {
            if (!_instances.ContainsKey(key)) _instances.Add(key, new Multiton());
        }
        return _instances[key];
    }
}

Note that the GetMultiton method uses a lock around the code that checks for the existence of the provided key and creates a new instance when required. This adds thread-safety to the class, ensuring that two threads simultaneously requesting an object linked to a single key do not attempt to create two separate instances.

Example Multiton

In this section we'll create an example multiton representing the security cameras described earlier. The Camera class below includes the code of the design pattern, using an integer parameter to provide the key. In this case there is no limit on the number of cameras that can be instantiated, other than the limitations of the memory installed in the computer or the maximum number of unique integer values. If you wish to include limits you would add them to the GetCamera method.

The Camera class adds a property named, "HardwareId" that in the real solution would be read from the physical camera. To simulate this, the property the class uses a globally unique identifier (GUID). This GUID will be different for each physical camera. Two camera objects generated from the same key should have the same GUID.

NB: The properties in the sample code are defined using the .NET 3.0 automatically implemented property syntax. If you are using .NET framework 2.0, you should expand these to include a backing store.

public sealed class Camera
{
    static Dictionary<int, Camera> _cameras = new Dictionary<int, Camera>();
    static object _lock = new object();

    private Camera() 
    {
        HardwareId = Guid.NewGuid();
    }

    public static Camera GetCamera(int cameraCode)
    {
        lock (_lock)
        {
            if (!_cameras.ContainsKey(cameraCode)) _cameras.Add(cameraCode, new Camera());
        }
        return _cameras[cameraCode];
    }

    public Guid HardwareId { get; private set; }
}

Testing the Multiton

We can demonstrate that only one instance is generated for each unique key by creating several objects, some of which share a camera number. Outputting the HardwareId property value will show which objects share a reference.

Try running the following code. The GUIDs that you see will be different to those in the comment. However, you should note that the GUIDs for cameras generated using the same ID match.

Camera cam1a = Camera.GetCamera(1);
Camera cam1b = Camera.GetCamera(1);
Camera cam2a = Camera.GetCamera(2);
Camera cam2b = Camera.GetCamera(2);

Console.WriteLine(cam1a.HardwareId);
Console.WriteLine(cam1b.HardwareId);
Console.WriteLine(cam2a.HardwareId);
Console.WriteLine(cam2b.HardwareId);

/* OUTPUT

86f5983c-08ed-483a-1e79-26557c4bd4e1
86f5983c-08ed-483a-1e79-26557c4bd4e1
8a8b1350-3b11-432c-916e-4e5f8aea70ac
8a8b1350-3b11-432c-916e-4e5f8aea70ac

*/
3 March 2012