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.
using System.Collections.Generic;
namespace MyApplication {
class FooMultiton {
private static readonly Dictionary<object, FooMultiton> _instances = new Dictionary<object, FooMultiton>();
private FooMultiton() {
}
public static FooMultiton GetInstance(object key) {
lock (_instances) {
FooMultiton instance;
if (!_instances.TryGetValue(key, out instance)) {
instance = new FooMultiton();
_instances.Add(key, instance);
}
return instance;
}
}
}
}
No comments:
Post a Comment