Hello!
If you have a Java aggregate (as Eric Evans defines it) which contains a one to many relationship where every child object belongs to a certain aggregateRoot. How do you implement this in a way that the code expresses this relationship?
I came up with the following idea:
Code:
class aggregateRoot {
private List<Child> children = new ArrayList<Child>();
//Noone is allowed to modify the collection without the root knowing.
public List<Child> getChildren() {
return Collections.unmodifiableList(children);
}
public void removeChild(Child child) {
children.remove(child);
}
// New Childs can only be added to one aggregateRoot.
// There is no way to add a Child to more than one root.
public Child addNewChild() {
Child newChild = new Child();
children.add(newChild);
return newChild;
}
}
class Child {
// Properties....
// Child cannot live on its own, so only aggregateRoot can create a Child.
protected Child() {};
}
kind regards