[英]Parent child class relationship design pattern
我有一个包含子项列表的类。 是否有我可以复制的设计模式可以应用于这些类,以便我可以从子项访问父实例,并且它强制执行诸如不能将子项添加到多个父项等规则?
尝试复合设计模式:
https://www.dofactory.com/net/composite-design-pattern
要使用它,您必须添加一些代码以将树向上移动到它看起来像的父级,但除此之外它应该可以工作。
只需添加一个属性,该属性在将父元素添加到树中时保存对父元素的引用。 如果父节点更改,则更新它,如果删除节点,则将其设置为 null。
也许像这样的东西?
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;}
}
例如,您可以在任何语言的分层字典的帮助下使用复合设计模式来实现父(面板)子(按钮)关系! 这是示例python代码。
panel = DictObject('panel') button= window.addChild('button') textfield = button.addChild('Text')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.