使用复合设计模式对不同类型的对象进行操作,有没有办法防止一个对象被多次操作?

发布于 2024-10-07 04:02:35 字数 383 浏览 0 评论 0原文

我想使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

·深蓝 2024-10-14 04:02:35

我不知道你所说的惯用语是什么意思,但解决方案取决于你如何遍历复合材料的结构。 则可以选择以下一些选项:

  • 如果您使用访问者并记住已访问过的组件,
  • 使用滴答计数忽略重复项,并让复合元素
  • 在两步方法中忽略具有相同滴答计数的连续调用收集需要操作的所有复合对象在一组中打开,然后以两步方法执行操作
  • ,在复合对象中设置一个标志,表示本轮何时触摸它们,在下一轮之前清除该标志

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

  • if you use a visitor and remember the already visited components, ignore duplicates
  • use a tick count and have the composite element ignore successive calls with the same tick count
  • in a two step method gather all the composite objects that need to be operated on in a set and then perform your operation
  • in a two step method set a flag in your composite objects that signifies when they have been touched this round, clear the flag before the next round
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文