开发者

Using the composite design pattern to operate on objects of different type, is there a way to prevent an object from being operated on more than once?

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 obj开发者_Python百科ect'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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜