DDD:实体和值对象之间的区别有什么用? [英] DDD: what's the use of the difference between entities and value objects?

查看:452
本文介绍了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?

推荐答案

是的,能够分辨出差异非常有用,尤其是在设计和实现类型时.

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.

当相等语义众所周知时,它在单元测试中也有很大帮助.在这两种情况下,均等性是明确定义的.我不知道您使用哪种语言,但是在许多语言(C#,Java,VB.NET)中,默认情况下,相等性是由引用确定的,在许多情况下,它并不是特别有用.

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.

这篇关于DDD:实体和值对象之间的区别有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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