Demystifying Design Patterns — Multiton pattern
What is Multiton Pattern?
The Multiton Pattern is a creational design pattern that extends the concept of the Singleton Pattern. While the Singleton Pattern ensures that a class has only one instance and provides a global point of access to it, the Multiton Pattern goes a step further. It ensures a unique instance per key, maintaining a registry of instances indexed by keys. Each key corresponds to a distinct instance, allowing multiple instances of a class to coexist, each associated with a specific identifier.
Why Multiton Pattern?
a. Resource Management: The Multiton Pattern is particularly useful when dealing with limited resources that need to be shared across different components of an application. By associating each resource with a key, the pattern allows for efficient management and retrieval of instances based on contextual needs.
b. Configurable Instances: In scenarios where multiple instances of a class are required with different configurations or states, the Multiton Pattern allows for the creation and retrieval of instances with specific attributes. This makes it a flexible solution for managing objects with varied configurations.
c. Avoiding Global State: While Singleton promotes global access to an instance, Multiton provides a more controlled access mechanism. By using keys, it avoids the issues associated with global state and allows for a more modular and organized approach to handling instances.
When to use Multiton Pattern?
✓ Contextual Instances: Use the Multiton Pattern when you need to manage instances in a context-dependent manner, and each instance is uniquely identified by a key.
✓ Resource Pooling: When dealing with limited resources, such as database connections, thread pools, or network connections, the Multiton Pattern can efficiently manage and reuse instances based on their keys.
Get CodeChuckle’s stories in your inbox
Join Medium for free to get updates from this writer.
✓ Configurable Objects: For classes with multiple configurations or states, the Multiton Pattern allows you to create and retrieve instances with specific attributes as needed.
Variations & Code
1. Eager Initialization multiton
using System;
using System.Collections.Generic;
public class MultitonEager
{
private static readonly Dictionary<string, MultitonEager> instances = new Dictionary<string, MultitonEager>();
static MultitonEager()
{
// Eagerly create instances for all possible keys during class initialization
InitializeInstances();
}
private MultitonEager()
{
// Initialization code
}
public static MultitonEager GetInstance(string key)
{
if (!instances.ContainsKey(key))
{
// You can choose to throw an exception, return null, or create a default instance
throw new ArgumentException($"No instance found for key: {key}");
}
return instances[key];
}
private static void InitializeInstances()
{
// Create instances for all possible keys
instances["Key1"] = new MultitonEager();
instances["Key2"] = new MultitonEager();
// Add more instances as needed
}
public void Operation()
{
Console.WriteLine($"Performing operation on eager instance with key: {this.GetHashCode()}");
}
}Pros: Predictable Memory Usage, Reduced Latency on First Use
Cons: Increased Memory Usage, Application Startup Overhead, Not Suitable for Large Key Space
2. Lazy multiton
using System;
using System.Collections.Generic;
public class LazyMultiton
{
private static readonly Dictionary<string, LazyMultiton> instances = new Dictionary<string, LazyMultiton>();
private LazyMultiton()
{
// Initialization code
}
public static LazyMultiton GetInstance(string key)
{
if (!instances.ContainsKey(key) || instances[key] == null)
{
instances[key] = new LazyMultiton();
}
return instances[key];
}
}Pros: Efficient resource utilization, reduced startup overhead
Cons: Potential increased latency on first use, thread safety concerns in multithreaded environments
3. Thread-safe lazy multiton
using System;
using System.Collections.Concurrent;
public class Multiton
{
private static ConcurrentDictionary<string, Multiton> instances =
new ConcurrentDictionary<string, Multiton>();
private Multiton() { }
public static Multiton GetInstance(string key)
{
return instances.GetOrAdd(key, _ => new Multiton());
}
}Pros: Ensures safe concurrent access to instances, suitable for high-concurrency scenarios
Cons: Potential for increased contention due to locking, may impact performance in high-throughput situations
When not to use Multiton Pattern
✘ Overhead for Small-Scale Applications: In smaller projects, the overhead of maintaining a registry for Multiton instances may outweigh the benefits; simpler patterns like Singleton or regular instantiation could be more suitable.
✘ Unnecessary Complexity: When uniqueness based on keys is unnecessary, implementing the Multiton Pattern may introduce unnecessary complexity to the code; simpler alternatives should be considered.
✘ Global State is Acceptable: If global access to a single instance suffices and context-dependent instances are not needed, the traditional Singleton Pattern might be sufficient, avoiding the added complexity of the Multiton.
In summary, the Multiton pattern is a variation of the Singleton pattern, providing a unique instance for each distinct key. It’s particularly useful when managing context-specific instances or limited resources, offering flexibility in configurations. However, for small-scale applications or when simplicity is crucial, it might introduce unnecessary complexity. Careful consideration of the application’s scale and requirements is necessary to determine whether the Multiton pattern is the most suitable solution.
This content was crafted with the invaluable assistance of ChatGPT.
Please ensure to express your support by giving my blog post a 👏 and following my account. Your gestures not only bring me satisfaction in knowing I’ve aided fellow developers but also serve as motivation to persist in my writing endeavors.






