开发者

to pass data around using event handling

Anyone can detail the pro开发者_运维知识库s and cons to pass data from one class to another using event mechanism? When is the best time to use event to pass data?


Let's take an example. You have a system where 20 people are subscribed to a weather station for changes in weather. Do you want the weather station to keep track of all the people and services that are subscribed?

In my opinion the weather station should not know anything about the people or services that are waiting for weather changes. The weather station should just dispatch an event, and whoever is listening to it will get notified :-)

So the point is, you use events to notify observers about an action or state change that occurred in the object. Observers can be difference type of objects since you don't have to know anything about them. If someone listens to the object, then he takes care of it.

If it was one to one relation and the object waiting for something to happen is always of the same type, then you wouldn't really need an event for that case.

Events are also great to decouple systems, like seen in my example above with the weather station. The weather station can run on its own without knowing about the services or users that are listening to it.


Using events will among other things:

  • Decouple the event source from the event receiver
  • Allow multiple event receivers to subscribe to the same event
  • Provide a well known pattern for implementing eventing

One thing to be aware of is how delegates may create unexpected "leaks" in your code: Memory Leak in C#.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜