我想知道两个实现之间的区别。
public class ShoppingBasket
{
...
public Guid Id { get; private set; }
// encapsulated mutable state
private List<BasketItem> Items { get; set; }
public void Add(BasketItem item)
{
if (this.Items.Contains(item))
throw new DuplicateItemSelected();
else
this.Items.Add(item); // mutating state
}
...
}
和
public struct ShoppingBasket
{
public ShoppingBasket(Guid id, IImmutableList<BasketItem> items)
{
this.Id = id;
this.Items = items;
}
public Guid Id { get; private set; }
public IImmutableList<BasketItem> Items { get; private set; }
}
// all functions for the Basket aggregate
public static class Basket
{
// pure function, does not belong to any object instance
public static ShoppingBasket AddItem(BasketItem item, ShoppingBasket basket)
{
if (basket.Items.Contains(item))
throw new DuplicateItemSelected();
// adding creates a new immutable collection
IImmutableList<BasketItem> items = basket.Items.Add(item);
// create a new immutable basket
return new ShoppingBasket(basket.Id, items);
}
}