我有一个类,为了控制如何创建实例和确保唯一值,我在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;
}
}
Run Code Online (Sandbox Code Playgroud)
我现在还有一些具有相同原理的课程.这里不可能继承所有类将共享相同的Dictionary.
那么有一种方法可以重用代码吗?
根据您发布的内容,您可以将其设为通用:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我Factory使用Flyweight Factory模式调用了类a
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |