域驱动设计不同的实现

时间:2019-04-17 10:57:57

标签: domain-driven-design

我想知道两个实现之间的区别。

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);
    }
}

0 个答案:

没有答案