KeyedByTypeCollection<object> collection = new KeyedByTypeCollection<object>();
collection.Add("Car");
collection.Add(1);
collection.Add(1.1);
collection.Add("Dog"); // Aceasta linie o sa arunce exceptie.
Ultima linie o sa arunce exceptie deoarece avem deja in colectie un element de tip string. La prima vedere aceasta colectie pare destul de ciudata si poate genera urmatoarea intrebare:La ce este folositoare?Un scenariu in care aceasta colectie poate sa foarte folositoare este cand vrem sa avem un factory care sa pastreze obiectele ca si singleton. Folosind aceasta colectie implementarea factory poate sa aibe urmatoarea forma:
public class SingletonFactory<T>
{
private readonly KeyedByTypeCollection<T> _items = new KeyedByTypeCollections<T>();
public TItem GetObject<TItem>()
where TItem : T, new()
{
if(!_items.Contains(typeof(TItem))
{
_items.Add(new TItem));
}
return (TItem)_items[typeof(TItem)];
}
}
In ce alte scenarii de utilizare ati folosii aceasta colectie?Enjoy!
0 comments:
Post a Comment