【发布时间】:2013-05-23 14:09:17
【问题描述】:
有人可以检查这个版本的 Generic Multiton 是否是惰性和线程安全的?
我根据Jon Skeet's version of a lazy thread safe Singleton、O'Reilly 的 C# 设计模式和 Multiton 的维基百科 C# 版本对其进行了编码。
public sealed class Multiton<T> where T : class, new() {
private static readonly Dictionary<object, Lazy<T>> _instances = new Dictionary<object, Lazy<T>>();
public static T GetInstance(object key) {
Lazy<T> instance;
if (!_instances.TryGetValue(key, out instance)) {
instance = new Lazy<T>(() => new T());
_instances.Add(key, instance);
}
return instance.Value;
}
private Multiton() {
}
}
【问题讨论】:
-
Isn't a mutliton just a singleton dictionary.
-
@DanielHilgarth 为什么?它不是要求最好的方法来改进它。它是在询问代码是否可以正常工作。
-
@Servy:他要求进行代码审查。
-
@DanielHilgarth 不,代码审查几乎是在说,“那么我的代码怎么样,可以做些什么来使它变得更好”,而这是询问特定的、范围狭窄的属性程序和关于该财产是否存在的客观分析。完全适合 SO。
标签: c# multithreading design-patterns