4

我有一个名为 Person 的聚合根。该人也有一个地址。这些类之间的关系是ManyToOne(许多人共享同一个地址)。

这意味着当我使用工厂创建具有特定地址的新人员时,我必须检查数据库中是否已经存在相同的地址并为用户使用现有地址。

这要求我的工厂可以访问地址存储库(或直接访问数据库)。这是允许的吗?如果没有,有什么更好的方法来做到这一点?

//编辑我的解决方案现在如下:

我有一个 PersonService 类,它包含注册一个人的逻辑。该方法register()已经采用了由 AddressFactory 创建的地址对象。Addressfactory 可以访问 AddressRepository 来检查输入的地址是否已经存在。这是代码:

public class PersonService{

  @Inject private PersonRepository pRepo;

  public Person register(Name name,..., Address address){
      //check if same person exists,
      //create person, persist person
      return person;
  }
}

public class AddressFactory{
   @Inject AddressRepository aRepo;

   public Address create(String street, int number, ...){
      //check if address with attribues exists in repo,
      //if not create new address
      return address;
   }
}

在某些 bean 中,这个方法是这样调用的:

personService.register(new Name("test"),..., addressFactory.create("Some street", 1,...))

你怎么看?

4

2 回答 2

4

This means that when I'm creating a new Person with a specific address using a factory, I'd have to check if a same address already exists in the database and use an exisiting address for the user.

If you follow the Single Responsibility Principle to the letter, you shouldn't do that. PersonFactory isn't supposed to create Addresses but Persons.

Even less so when Address creation includes complex logic such as retrieving an Address in the database that resembles more or less the address that was filled in by the user (if that's really what you want). You should delegate that to another object.

于 2013-04-08T12:28:50.370 回答
1

是的,就 Person 的存储库(而不是 Person 本身)使用工厂而言,这是一个有效的解决方案。

但是,您应该考虑,在您的域模型中,Person 是否真的需要他们的地址来确保业务不变量。如果不是,请从人员中删除地址并使用专门为此类投影范围定义的PersonDTO 。

于 2013-04-08T10:41:18.180 回答