DDD:如何构造或解决域实体中更复杂的行为? [英] DDD: How do structure or resolve more complex behaviour in a domain entity?

查看:45
本文介绍了DDD:如何构造或解决域实体中更复杂的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设经典的Order/OrderLine业务情景.

Assume the classic Order/OrderLine scenario.

public class Order {
 ...
    public void AddOrderLine(OrderLine ol) {
        this.OrderLines.Add(ol);
        UpdateTaxes();
    }


    private void UpdateTaxes() {
        //Traverse the order lines
        //Collect the VAT amounts etc
        //Update totals 
        var newTaxes = Orderlines.SelectMany(ol => ol.GetTaxes());
        Taxes.Clear();
        Taxes.Add(newTaxes);

    }

}

现在,我们认为我们需要更好地处理税收,对不同国家/地区的客户有不同的处理方式,其中一些国家需要收取增值税,而其他国家则不需要收取增值税.

Now, we figure that we need to handle taxes better, with different ways for customers in various countries etc, where some require VAT to be collected and others not.

简而言之,税收规则将取决于客户的位置,购买的物品等.我们将如何做?我们是否应该在UpdateTaxes中放入很多代码?我们可以使用税收计算器工厂并在UpdateTaxes中引用它吗?

In short, the tax rules will depend on the customer's location, items purchased etc. How would we do this? Should we put a lot of code into UpdateTaxes? Could we use tax calculator factory and reference it in UpdateTaxes?

private void UpdateTaxes() {
    var taxRules = TaxRulesFactory.Get(this);
    var taxes = taxRuleCalc.Apply(this);
    Taxes.Clear();
    Taxes.Add(taxes);
}

推荐答案

考虑到有关AR中复杂行为的更广泛的问题,处理此问题的首选方法是使用双分派.请记住,如果复杂的行为具有凝聚力,则可以将 包含在AR中.

Considering your broader question regarding complex behaviour in ARs the preferred way to handle this would be to use double-dispatch. Bear in mind that complex behaviour certainly can be included in the AR if that behaviour is cohesive.

但是,对于要根据税收甚至折扣计算的程度而变化的功能,在其中实施各种策略的情况,您可以选择双重派发:

However, for functionality that varies to the degree of tax or even discount calculation, where one would implement various strategies, you could opt for the double dispatch:

public class Order
{
    public void ApplyTax(ITaxService taxService)
    {
        _totalTax = taxService.Calculate(TotalCost());
    }

    public void ApplyDiscount(IDiscountService discountService)
    {
        _discount = discountService.GetDiscount(_orderLines.Count, TotalCost());
    }

    public Money TotalCost()
    {
        // return sum of Cost() of order lines
    } 
}

这些服务也不应注入到AR中,而应传递到相关方法中.

These services also should not be injected into the AR but rather passed into the relevant method.

这篇关于DDD:如何构造或解决域实体中更复杂的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆