2011-07-28 40 views
-1

工作,如果我有一个聚合对象如订单 - >订单行,其中我的订单对象被确定为总根,因而增加订单行到我期望通过聚合根这样做的秩序,并没有其他的手段例如Order.AddOrderLine(OrderLine行)。与集合C#

订单对象显然暴露出OrderLines的集合,但我要如何避免使用此集合直接添加OrderLines消费者,我认为答案是使用一个只读集合?这是否会阻止消费者改变对象的状态,即集合中的OrderLines?

感谢

+0

你可以发布代码? –

+3

正在Readonly集合中不会阻止消费者更改其中的对象。 –

+0

为什么你不希望人们直接添加订单? –

回答

5

暴露你的orderLines为IEnumerable <订单行>和实施添加/删除必要的方法。这样你的客户只能在集合上进行迭代,而不是通过你的聚合来操纵它。

+0

现货!非常感谢。 – David

0

如果你不想暴露你的订单行对象,您应该想传递一个订单行到您的订单,例如另一种方式只提交元信息在一个单独的类如下面我的例子:

/// <summary> 
/// Represents an order, order lines are not accessible by other classes 
/// </summary> 
public class Order 
{ 
    private readonly List<OrderLine> _orderLines = new List<OrderLine>(); 

    public void AddOrderLineFromProperties(OrderLineProperties properties) 
    { 
     _orderLines.Add(properties.CreateOrderLine()); 
    } 
} 

/// <summary> 
/// Class which contains orderline information, before it is 
/// "turned into a real orderline" 
/// </summary> 
public class OrderLineProperties 
{ 
    public OrderLine CreateOrderLine() 
    { 
     return new OrderLine(); 
    } 
} 

/// <summary> 
/// the concrete order line 
/// </summary> 
public class OrderLine 
{ 

}