使用策略配置 DDD 聚合的行为

Configure behaviour of DDD aggregate with strategies

我有一个汇总:

public class MyAggregate {

    private Country country;
    private List<SomeEntity> someEntities;

    public SomeEntity getBestMatchingSomeEntity();

}

我的问题是,getBestMatchingSomeEntity() 的行为应该根据国家/地区进行配置,因此我喜欢使用策略(简单 Spring bean)。

我不确定如何 "inject" 我的实体中的策略。通常我会使用某种 selector,但我不想在我的实体中注入服务。或者我应该在创建实体时 select 正确的策略并将策略注入实体吗?或者域服务是可行的方法吗?

谢谢!

为了保持聚合尽可能干净,它应该有自己用来检查其不变量的行为。一些领域服务应该包含复杂的查询行为。

在您的情况下,您应该有一个域服务,该域服务已注入策略或作为方法参数传递,具体取决于所需的配置。

如果您使用 CQRS,这种分离会更加清晰,其中读取模型将承担此责任。

我脑海中首先浮现的是

你为什么没有接受这样的服务的方法:

public class MyAggregate {

    private Country country;
    private List<SomeEntity> someEntities;

    public SomeEntity getBestMatchingSomeEntity(MatchingEntityService service);
}

然后您将服务定义为:

 public interface MatchingEntityService {

     SearchEntityStrategy strategyFor(Country country);

 }

这样在你的聚合中你可以使用该服务而没有注入问题,以及亲属序列化问题。

MatchingEntityService 将具有 select 基于 Country 的正确策略的逻辑,您可以将所有不同的策略分开。