Parent Class Relationship Template

I have a class that has a list of children. Is there a design pattern that I can copy that I can apply to these classes to access the parent instance from the child, and it applies rules such as the inability to add a child to multiple parents, etc.?

+3
source share
3 answers

Try the composite design template:

http://www.dofactory.com/Patterns/PatternComposite.aspx

To use this, you need to add some code to move the tree to the parent, what it looks like, but besides that it should work.

, , . , , null, node.

+2

- ?

public class Parent
{
   public Parent()
   {
     _children = new List<Child>();
    }

   private IList<Child> _children;
   public IEnumerable<Child> Children
   {
     get
     {
       return _children;
     }
   }

   public void Add(Child child)
{
    if (_children.Contains(child)) return;
    if (child.Parent != null && child.Parent !=this) throw new Exception ("bla bla bla");
    _children.Add(child);
    child.Parent = this;
}

public void Remove (Child child)
{
   child.Parent = null;
   _children.Remove(child)
{

}

public class Child
{
  public Parent Parent
  {
     get { return _parent;}
     protected internal set { _parent = value;}
}
+1

for example, you can implement a child (child) relationship of a parent (panel) using a composite design pattern using hierarchical dictionaries in any language! Here is a python code example.

panel = DictObject ('panel') button = window.addChild ('button') textfield = button.addChild ('Text')

0
source

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


All Articles