DDD 服务或实体对礼品卡金额减少进行建模
我正在尝试考虑可以使用 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.
}
}
I'm trying to think of a gift card example that I could model using DDD. For example, I have a gift card entity. In my system at some point, a gift card amount is going to need to be reduced or redeemed. Would I use a gift card service object to reduce the amount? The service would include validating the incoming amount and making sure the new amount isn't more than the balance, ect. Or would this live right on my gift card entity as another method and then just pass my updated gift card object to my repository to persist?
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.
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您可能希望这些属性是只读的。这样,
Id
和Amount
不能仅通过设置值来更改。接下来,您需要一种针对礼品卡进行交易的方法。这些交易将相应地借记调整金额。像这样的事情:
请记住,这只是众多设计选项之一。
To start, you probably want the properties to be read-only. This way the
Id
andAmount
cannot change just by setting the value.Next, you will need a way to place transactions against the gift card. These transactions would debit adjust the amount accordingly. Something like this:
Keep in mind this is just one of many design options.
行为应该在实体上。此外,Id 和 Amount 应该是具有公共访问者的私有成员。所以它看起来像这样:
The behaviour should be on the entity. Also, the Id and the Amount should be private members with public accesser. So it would look like this:
在这种情况下,我倾向于将此逻辑放在域对象上。实际上,我并没有真正开始使用服务,除非域模型中引入了一些依赖项,例如:
在本例中,我将拥有一个用户注册服务。
然而,在您的情况下,让域对象足够智能来验证其自身属性的设置将使生活变得更加容易。
In situations like this I lean toward putting this logic right on the domain object. I actually don't really start using services unless some dependency will be introduced to the domain model, for example:
in this case I would have a user registration service.
In your situation however, it will make life a lot easier to just have the domain object smart enough to validate setting its own properties.