我有一个类,为了控制如何创建实例并确保唯一值,我在Class中做了以下内容:
这里的例子:
class Foo
{
private Foo() { }
private static Dictionary<string, Foo> FooCollection = new Dictionary<string, Foo>();
public static Foo GetFoo(string key)
{
Foo result;
if (FooCollection.TryGetValue(key, out result) == false)
{
result = new Foo();
FooCollection.Add(key, result);
}
return result;
}
}
我现在还有一些具有相同原理的课程。这里不可能继承所有类将共享相同的Dictionary。
所以有一种方法可以重用代码吗?
答案 0 :(得分:6)
根据您发布的内容,您可以将其设为通用:
class Factory<T> where T:new()
{
private Factory() { }
private static Dictionary<string, T> Inventory = new Dictionary<string, T>();
public static T GetObject(string key)
{
T result;
if (Inventory.TryGetValue(key, out result) == false)
{
result = new T();
Inventory.Add(key, result);
}
return result;
}
}
请注意,我将班级称为Factory
,因为它使用的是Flyweight Factory pattern