views:

106

answers:

3

I have a class which has a list of child items. Is there a design pattern I can copy that I can apply to these classes so that I can access the parent instance from the child, and it enforces rules such as not being able to add the child to multiple parents, etc?

+2  A: 

Try the composite design pattern:

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

To use this, you'll have to add some code in to move back up the tree to the parent it looks like, but other than that it should work.

Just add a property that holds a reference to the parent element when it is added to the tree. Update it if the parent changes, and set it to null if the node is removed.

Kevin
A: 

for example you could implement parent(panel) child(button) relationship by using composite design pattern with the help of hierarchical dictionaries in any language! here is sample python code.

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

Sudhakar Kalmari
A: 

Something like this maybe?

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;}
}
epitka