且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

家长小孩班关系设计模式

更新时间:2023-09-11 23:11:46

尝试复合设计模式:



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



为了使用这个,你必须添加一些代码来将树移回到它看起来像这样的父类,但是除此之外它应该可以工作。



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


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?

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.