Creo que la forma más común de agregar algo a una colección es usar algún tipo de método Add
que proporciona una colección:
class Item {}
var items = new List<Item>();
items.Add(new Item());
y en realidad no hay nada inusual en eso.
Sin embargo, me pregunto por qué no lo hacemos de esta manera:
var item = new Item();
item.AddTo(items);
parece ser de alguna manera más natural que el primer método. Esto tendría la ventaja de que cuando la clase Item
tenga una propiedad como Parent
:
class Item
{
public object Parent { get; private set; }
}
puedes hacer que el setter sea privado. En este caso, por supuesto, no puede utilizar un método de extensión.
¿Pero quizás me equivoque y nunca haya visto este patrón antes porque es tan poco común? ¿Sabe si existe algún patrón de este tipo?
En C#
, un método de extensión sería útil para eso
public static T AddTo(this T item, IList<T> list)
{
list.Add(item);
return item;
}
¿Qué hay de otros idiomas? Supongo que en la mayoría de ellos la clase Item
tuvo que proporcionar una interfaz que llamamos ICollectionItem
.
Update-1
Lo he estado pensando un poco más y este patrón sería muy útil, por ejemplo, si no quieres que se agregue un elemento a varias colecciones.
prueba ICollectable
interface:
interface ICollectable<T>
{
// Gets a value indicating whether the item can be in multiple collections.
bool CanBeInMultipleCollections { get; }
// Gets a list of item's owners.
List<ICollection<T>> Owners { get; }
// Adds the item to a collection.
ICollectable<T> AddTo(ICollection<T> collection);
// Removes the item from a collection.
ICollectable<T> RemoveFrom(ICollection<T> collection);
// Checks if the item is in a collection.
bool IsIn(ICollection<T> collection);
}
y una implementación de ejemplo:
class NodeList : List<NodeList>, ICollectable<NodeList>
{
#region ICollectable implementation.
List<ICollection<NodeList>> owners = new List<ICollection<NodeList>>();
public bool CanBeInMultipleCollections
{
get { return false; }
}
public ICollectable<NodeList> AddTo(ICollection<NodeList> collection)
{
if (IsIn(collection))
{
throw new InvalidOperationException("Item already added.");
}
if (!CanBeInMultipleCollections)
{
bool isInAnotherCollection = owners.Count > 0;
if (isInAnotherCollection)
{
throw new InvalidOperationException("Item is already in another collection.");
}
}
collection.Add(this);
owners.Add(collection);
return this;
}
public ICollectable<NodeList> RemoveFrom(ICollection<NodeList> collection)
{
owners.Remove(collection);
collection.Remove(this);
return this;
}
public List<ICollection<NodeList>> Owners
{
get { return owners; }
}
public bool IsIn(ICollection<NodeList> collection)
{
return collection.Contains(this);
}
#endregion
}
uso:
var rootNodeList1 = new NodeList();
var rootNodeList2 = new NodeList();
var subNodeList4 = new NodeList().AddTo(rootNodeList1);
// Let's move it to the other root node:
subNodeList4.RemoveFrom(rootNodeList1).AddTo(rootNodeList2);
// Let's try to add it to the first root node again...
// and it will throw an exception because it can be in only one collection at the same time.
subNodeList4.AddTo(rootNodeList1);