DDD:实体和值对象的区别有什么用?
实体和值对象都是领域对象。在 DDD 中知道两者的区别有什么用呢?例如,将域对象视为实体或值对象是否会促进更清晰的域模型?
Entities and value objects are both domain objects. What's the use of knowing the distinction between the two in DDD? Eg does thinking about domain objects as being either an entity or value object foster a cleaner domain model?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,能够区分差异非常有帮助,特别是在设计和实现类型时。
主要区别之一是在处理相等性时,因为实体应该具有与值对象完全不同的行为。了解您的对象是实体还是值对象可以告诉您应该如何实现类型的相等性。这本身很有帮助,但还不止于此。
实体是可变类型(至少从概念上来说)。实体背后的整个想法是,它代表一个具有已知生命周期进程的域概念(即,它被创建,它经历多次转换,它被归档,也许最终被删除)。它代表相同的特定“事物”,即使数月或数年过去了,并且它的状态一直在改变。
另一方面,值对象仅表示没有任何固有标识的值。尽管您不必这样做,但它们非常适合作为不可变类型实现。这非常有趣,因为任何不可变类型根据定义都是线程安全的。当我们进入多核时代时,知道何时将对象实现为不可变类型非常有价值。
当相等语义众所周知时,它对单元测试也有很大帮助。在这两种情况下,平等都是明确定义的。我不知道你使用什么语言,但在许多语言(C#、Java、VB.NET)中,默认情况下相等性是通过引用确定的,这在许多情况下并不是特别有用。
Yes, it is very helpful to be able to tell the difference, particularly when you are designing and implementing your types.
One of the main differences is when it comes to dealing with equality, since Entities should have quite different behavior than Value Objects. Knowing whether your object is an Entity or a Value Object tells you how you should implement equality for the type. This is helpful in itself, but it doesn't stop there.
Entities are mutable types (at least by concept). The whole idea behind an Entity is that it represents a Domain concept with a known lifetime progression (i.e. it is created, it undergoes several transformations, it is archived and perhaps eventually deleted). It represents the same particular 'thing' even if months or years pass by, and it changes state along the way.
Value Objects, on the other hand, simply represent values without any inherent identity. Although you don't have to do this, they lend themselves tremendously well to be implemented as immutable types. This is very interesting because any immutable type is by definition thread-safe. As we are moving into the multi-core age, knowing when to implement an object as an immutable type is very valuable.
It also helps a lot in unit testing when the equality semantics are well-known. In both cases, equality is well-defined. I don't know what language you use, but in many languages (C#, Java, VB.NET) equality is determined by reference by default, which in many cases isn't particularly useful.