Heirachy:
LineEntityType
SingleLineEntity
BlockEntity
Blocks can contain other blocks or single line entities. All entities can have a parent, which is always a BlockEntity
I want to do something like this:
BlockEntity rootBlock = new BlockEntity(...);
block.assignChildren(new LineEntityType[] {
new SingleLineEntity(...)
new BlockEntity(...)
new BlockEntity(...)});
so the parent block object (rootBlock
) duplicates each child (defensive copies) and at the same time adds itself as the parent:
BlockEntity(LineEntityType[] children) {
for(LineEntityType[] children) {
//Duplicate the array
childEntitiesWithParentAssigned = Arrays.copyOf(children, children.length);
//Duplicate each child, adding "this" as the parent
for(int i = 0; i < children.length; i++) {
child = childEntitiesWithParentAssigned[i];
childEntitiesWithParentAssigned[i] = child.getCopyWithParentAssigned(this);
}
}
}
This is what I have so far, but it's unacceptable because the parent class, LineEntityType
has multiple references to the child type, BlockEntity
(circular dependency).
public abstract class LineEntityType {
private final BlockEntity parent;
public LineEntityType(...) {
this(..., null); //Root entity
}
public LineEntityType(..., BlockEntity parent) {
this.parent = parent;
}
...
public abstract LineEntityType getCopyWithParentAssigned(BlockEntity parent);
}
The only other thing I've come up with is to explicitely assign the parent before assigning its children:
//null: No parent
BlockEntity rootBlock = new BlockEntity(..., null);
LineEntityType children = new LineEntityType[] {
new SingleLineEntity(..., rootBlock)
new BlockEntity(..., rootBlock)
new BlockEntity(..., rootBlock)});
rootBlock.setChildren(children);
But this requires the children field to be mutable.
Any ideas on how to rethink this, so the parent-field can be assigned by the parent, yet be immutable and avoid circular dependencies?
Thanks.