我有一个带有属性Id的Foo类.我的目标是同时没有两个具有相同Id的Foo实例.
所以我创建了一个工厂方法CreateFoo,它使用缓存来为同一个Id返回相同的实例.
static Foo CreateFoo(int id) {
Foo foo;
if (!cache.TryGetValue(id, out foo)) {
foo = new Foo(id);
foo.Initialize(...);
cache.Put(id, foo);
}
return foo;
}
Run Code Online (Sandbox Code Playgroud)
缓存实现为Dictionary <TKey,WeakReference>,基于@JaredPar的Building a WeakReference Hashtable:
class WeakDictionary<TKey, TValue> where TValue : class {
private readonly Dictionary<TKey, WeakReference> items;
public WeakDictionary() {
this.items = new Dictionary<TKey, WeakReference>();
}
public void Put(TKey key, TValue value) {
this.items[key] = new WeakReference(value);
}
public …Run Code Online (Sandbox Code Playgroud)