父子类关系设计模式

我有一个包含子项列表的类。 是否有我可以复制的设计模式,我可以应用于这些类,以便我可以从子进入父实例,并强制执行规则,如无法将子项添加到多个父项等?

尝试复合设计模式:

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

要使用它,您必须添加一些代码以将树移回到它看起来的父级,但除此之外它应该工作。

只需添加一个属性,该属性在将父元素添加到树中时保存对父元素的引用。 如果父更改,则更新它,如果删除该节点,则将其设置为null。

这样的事可能吗?

public class Parent { public Parent() { _children = new List(); } private IList _children; public IEnumerable 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;} } 

例如,你可以在任何语言的分层词典的帮助下使用复合设计模式实现父(面板)子(按钮)关系! 这是示例python代码。

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