使用复合设计模式对不同类型的对象进行操作,有没有办法防止一个对象被多次操作?
我想使用 C++ 中的复合设计模式来创建和操作对象组。我遇到的一个问题是,由于叶子和复合材料被视为相同,并且复合材料可以由叶子和复合材料组成,因此当向复合材料发出命令时,很可能对一个对象进行多次操作。
例如,复合group1包含对象A和B。然后创建一个包含复合group1和对象A的复合group2。对复合group2进行操作时,对象A将被操作两次。对于某些应用程序,我想这不是问题,但对于我的使用,我希望对于向复合体发出的任何命令,唯一的对象仅操作一次。
是否有一种惯用的方法来处理这个问题,要么阻止多次调用对象的成员函数,要么阻止对象多次包含在组合中?
-
更新: 我所说的“惯用”是指处理此类问题的“传统”或“公认”方式。 我想我只是假设/希望这是一个有既定解决方案的常见问题。
I'd like to use the Composite design pattern in C++ to be able to create and operate on groups of objects. A problem I've encountered is that since leaves and composites are treated the same, and composites can be comprised of leaves and composites, it is quite possible for an object to be operated on more than once when a command is issued to a composite.
For example, a composite group1 contains objects A and B. Then, a composite group2 is created containing composite group1 and object A. When composite group2 is operated on, object A will be operated on twice. For some applications I guess this isn't a problem, but for my uses I'd like it if, for any command issued to a composite, unique objects are only operated on once.
Is there an idiomatic way to deal with this problem, either some how preventing multiple calls of an object's member function, or preventing an object from being included in a composite more than once?
--
Update:
By "idiomatic" I mean "traditional" or "accepted" way of handling this type of problem.
I guess I'm just assuming/hoping this is a common problem that has an established solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道你所说的惯用语是什么意思,但解决方案取决于你如何遍历复合材料的结构。 则可以选择以下一些选项:
I don't know what you mean by idiomatic, but a solution would depend on how yo traverse the structure of composites. Here are some options