简体   繁体   中英

Tiered Event Handlers

Let's say I have a box. In the box are a bunch of envelops. In each envelop, there are a number of index cards. If I write something on one index card, every index card in the whole box should execute the method foo().

The way I see it, the index card should tell its envelop that something happened. Its envelop should tell the box that something happened to one of its index cards. The box tells all the envelops to tell all their index cards to execute method foo().

I'm relatively unfamiliar with C#'s event handler / delegate functionality. From what I can tell, this seems to be a good use for them. Are delegates the way to go here, or is there a better way? How would you tease out the framework for multi-level event handlers? Any insight would be appreciated.

If you do want to use event handlers then you have to remember that an object (in this case your index card) 'owns' an event and triggers it. It should not care who or what is listening. So then it does not care if index card, envelopes or anything else is listening it just triggers them.

If I assume that a box has a list of envelopes in contains (or index cards), and envelopes have a list of index cards it contains then you could either;

  1. The box listens for events, and enumerates every envelope it contains which enumerates every index card to do the update.
  2. The envelopes listen for events and enumerates every index card they contain to do the update
  3. Every index card listens for events and updates itself.

But, the problem I see with this approach is that the number of index cards could be high. So you could have a lot of index cards listening to a lot of other index cards.

I think it is better in this case to go for the publish/subscribe method suggested by Rob. So you implement a message queue, and then the changed index card publishes the change on here, and everything else that listens gets informed of the change. This would be a better approach.

But I think your question is a bit hypothetical, so you can take the event based approach for a smaller implementation maybe when you have a small number of objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM