Is it bad practice for a child object to have a pointer to its parent?

前端 未结 7 1746
我寻月下人不归
我寻月下人不归 2020-12-20 12:27

In a C++ application, let\'s say I have a window class, which has several instances of a control class. If my window wanted to notify a control that it had been clicked, I m

7条回答
  •  既然无缘
    2020-12-20 12:56

    In fact the GOF Composite design pattern is based on Explicit Parent References.

    Explicit parent references. Maintaining references from child components to their parent can simplify the traversal and management of a composite structure. The parent reference simplifies moving up the structure and deleting a component. Parent references also help support the Chain of Responsibility (223) pattern. The usual place to define the parent reference is in the Component class. Leaf and Composite classes can inherit the reference and the operations that manage it.

    With parent references, it's essential to maintain the invariant that all children of a composite have as their parent the composite that in turn has them as children. The easiest way to ensure this is to change a component's parent only when it's being added or removed from a composite. If this can be implemented once in the Add and Remove operations of the Composite class, then it can be inherited by all the subclasses, and the invariant will be maintained automatically.

    Therefore, I guess, there is a clear place for such a design, depending on the actual requirement and context.

提交回复
热议问题