我正在尝试考虑一个可以使用 DDD 建模的礼品卡示例。例如,我有一个礼品卡实体。在我的系统中,有时需要减少或兑换礼品卡金额。我可以使用礼品卡服务对象来减少金额吗?该服务将包括验证传入金额并确保新金额不超过余额等。或者这会作为另一种方法存在于我的礼品卡实体上,然后将我更新的礼品卡对象传递到我的存储库以保留?
public GiftCard
{
public int Id { get; set; }
public double Amount { get; set; }
}
public GifTCardService
{
public void ReduceAmount(GiftCard card, double amount)
{
// Validation checks to make sure amount can be removed.
// Call gift card repository to actually remove amount.
}
}
首先,您可能希望属性是只读的。这样,仅通过设置值就无法更改
Id
和 Amount
。
接下来,您需要一种针对礼品卡进行交易的方法。这些交易将相应地借记调整金额。像这样的东西:
class GiftCard
{
public long Id {get; private set;}
public double Amount {get; private set;}
public void Apply(Transaction tx)
{
if(tx.Amount > Amount)
{
handle insufficient funds
}
else
{
Amount -= tx.Amount;
//other logic if necessary
}
}
}
请记住,这只是众多设计选项之一。
行为应该在实体上。此外,Id 和 Amount 应该是具有公共访问者的私有成员。所以它看起来像这样:
public GiftCard
{
private int _id;
private double _amount;
public int Id
{
get { return _id; }
set { _id = value; }
}
public double Amount
{
get { return _amount; }
set { _amount = value; }
}
public void ReduceAmount(double amount)
{
// Validation checks to make sure amount can be removed.
...
//Reduce amount.
_amount -= amount;
}
}
在这种情况下,我倾向于将此逻辑放在域对象上。实际上我并没有真正开始使用服务,除非将一些依赖项引入到域模型中,例如:
set user to registered, and send email using some sort of email sending service
在这种情况下,我将有一个用户注册服务。
但是,在您的情况下,让域对象足够智能来验证设置其自己的属性会让生活变得更加容易。