自引用类作为聚合根 [英] Self-referencing Classes as Aggregate Roots

查看:35
本文介绍了自引用类作为聚合根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自引用和层次结构在现实世界的软件项目中并不少见.可以想到很多例子:

Self-referencing and hierarchical structures are not uncommon in real-world software projects. One can think of many examples:

  • 产品类别
  • 地理区域的树状结构

问题是,根据领域驱动设计原则,是否可以选择自引用类作为聚合根?你能举例说明它是如何实现的吗?

The question is, as of Domain-Driven Design principles, can a self-referencing class be selected as Aggregate Root? Can you give an example of how it can be implemented?

推荐答案

是否可以选择自引用类作为聚合根

can a self-referencing class be selected as Aggregate Root

如果我必须将一个大的分层同构树表示为一个聚合根,我很可能会为根实体引入一个不同的类(除了根是同构的),例如 CategoryRoot 1--* Category 1--* Category 不需要问这个问题.

If I had to express a large hierarchical homogeneous tree as an Aggregate Root I would most likely introduce a different class (homogeneous except for the root then) for the root entity, such as CategoryRoot 1--* Category 1--* Category which removes the need of asking this question.

如果你真的想要同一个类(不确定它是否可取),那么你仍然需要某种协议来确保根实例与子实体的处理方式不同,尽管它们是同一个类.例如,您只需要允许存储库返回顶级 Category(例如 parent = null)实例,而嵌套的 Category 实例不应不能在没有 root 的情况下访问或引用.

If you really want the same class (not sure if it's advisable) then you would still need some kind of protocol in place to make sure that the root instance is treated differently from child entities although they are the same class. For instance, you would need to only allow repositories to return top-level Category (e.g. parent = null) instances and nested Category instances shouldn't be made accessible nor referenced without their root.

这篇关于自引用类作为聚合根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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