在我看來,你正在嘗試創建一個對象庫,而不是工廠。對於存儲庫,在將對象添加到存儲庫之前,更容易實例化對象。
repository.Add(key, new SomeType(arg1, arg2));
如果要添加到庫中的所有對象從一個共同的類型派生或實現一些常用的接口,那麼簡單地用一個類型Dictionary<TKey, TValue>
。例如:
private Dictionary<string, IGameObject> _gameObjects =
new Dictionary<string, IGameObject>();
_gameObjects.Add("car", new Car(maxSpeed));
_gameObjects.Add("monster", new Monster());
並與檢索它:
IGameObject obj = _gameObjects(key);
如果打算存儲完全無關的類型,然後使用由所述類型和可能的標識符的化合物鍵。
public class Repository
{
private class RepositoryKey
{
public RepositoryKey(Type type, string key)
{
this.Type = type;
this.Key = key;
}
public Type Type { get; private set; }
public string Key { get; private set; }
//TODO: override Equals and GetHashCode.
}
private Dictionary<RepositoryKey, object> _dict =
new Dictionary<RepositoryKey, object>();
public void Add<T>(string key, T obj)
{
_dict.Add(new RepositoryKey(typeof(T), key), obj);
}
public Get<T>(string key)
{
return (T)_dict[new RepositoryKey(typeof(T), key)];
}
}
這只是一個簡單的實現,沒有錯誤處理。
var rep = new Repository();
rep.Add("slow", new Car(30));
rep.Add("fast", new Car(180));
rep.Add("left", new Monster(x1, y1));
rep.Add("right", new Monster(x2, y2));
...
Car fastCar = rep.Get<Car>("fast");
Monster leftMonster = rep.Get<Monster>("left");
檢查任何依賴注入容器。 – zerkms
是否有任何其他約束'T'從任何類型的接口或類派生,或'_internal_dict'只是一個'Dictionary'? –
我有點困惑。你想達到什麼目的?通常,工廠立即返回創建的類型。只有在工廠裏存儲單身人士纔有意義。工廠中的字典通常將類型(即不是實例的類)映射到接口或可能將類型(類)映射到某種類型的密鑰。你的代碼看起來更像是一個存儲庫。 –