How to create two objects with cyclic dependency?

If I have two objects, Parentand Child, Parentshould know about all its children Child, and each instance Childshould know about its parent instance Parent, how do I do it right (from the point of view of DDD, etc.)?

An easy way would be to do it parent.addChild(new Child(parent)), but it seems ugly - and also:

parent.addChild(new Child()); // Then call some setParent method on child, which needs to be public

Do I need to use a factory here? And if so, how?

thank

+3
source share
3 answers

- Parent. Factory, , , .

public class Parent {

    // ...

    public Child createChild() {
        Child c = new Child(this);
        this.addChild(c);
        return c;
    }

    protected void addChild(c) {
        // ...
    }

    // ...

}

public class Child {

    public Child(Parent p) {
        // ...
        this.addParent(p);
    }

    protected addParent(Parent p) {
        // ...
    }
}

Child , createChild.

+2

. , .

SWT :

new Label(parentComposite, SWT.NONE);

parentComposite .

: SWT , - . SWT.

Swing , .

, . .

, ( )

, :

Parent {
 addChild(Child child) {
  children.add(child);
  child.setParent(this);
 }
}

, . !

+2

How to do something like this:

public class Child {
   Child (Parent parent) {
      ... 
      this.parent = parent;
      parent.addChild(this);
   }
}

That way, you can only set the parent of the Child when creating the child.

+2
source

Source: https://habr.com/ru/post/1774478/


All Articles