我正在使用 DDD 模式开发应用程序。
我在域层中有 Invoice
类。
public class Invoice
{
List<InvoiceLine> list = new List<InvoiceLine>();
public DateTime Date { get; set; }
public Customer Customer { get; set; }
public decimal GrandTotal
{
get
{
// Simplified grand total.
// It's actually include tax and discount to calculate.
decimal total = 0m;
foreach(InvoiceLine line in Lines)
total += line.LineTotal;
return total;
}
}
public IEnumerable<InvoiceLine> Lines
{
get { return list; }
}
public void AddLine(InvoiceLine line)
{
lines.Add(line);
}
}
我正在使用 mvvm 模式,因此我还有一个 View 模型来编辑发票。我的问题是我应该将业务逻辑放在哪里来计算 GrandTotal,以便域和表示上的业务逻辑相同?
我应该将代码从域复制到演示文稿(Invoice
到 InvoiceViewModel
)吗?或者制作一个域和演示都可以使用的服务?
最佳答案
DDD 中聚合的主要目标是保持一致性 - 在您的情况下,一致性意味着例如 GrandTotal 将始终具有正确的值。也就是说,没有规则规定聚合类不能使用其他类来获得这种一致性。
例如,您可以提供一个类,其唯一职责是计算总计并在您的域和 View 模型中使用它。我不会将其称为服务,因为它与 DDD 概念无关。示例:
public interface IInvoiceLine
{
decimal Amount {get;}
}
public interface ICalculateGrandTotal
{
decimal Calculate(IEnumerable<IInvoiceLine> lines);
}
public class GrandTotalCalculator: ICalculateGrandTotal
{
...
}
现在您可以在 View 模型和域中使用此计算器,而无需重复代码。此外,由于接口(interface)的原因, View 模型和域类之间没有直接耦合。 IInvoiceLine
接口(interface)可以由 View 模型和域实体单独实现。
关于wpf - DDD 中领域层和表示层共享的业务逻辑应该放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15090937/