Consider the event as a callback interface, where the interface has only one method.
Use only the events you need
With events, you only need to implement handlers for events that you are interested in handling. In the observer interface template, you need to implement all methods in the entire interface, including implementing method bodies for notification types that you really do not need. In your example, you always need to implement OnFoundDirectory and OnFoundFile, even if you only need one of these events.
Less maintenance
Another good thing about events is that you can add a new one to a particular class so that it raises it, and you do not need to change every existing observer. If you want to add a new method to an interface, you need to go around all the classes that already implement this interface and implement the new method in all of them. However, with an event, you only need to modify the existing classes that actually want to do something in response to the new event that you are adding.
The template is built into the language so that everyone knows how to use it
Events are idiomatic because when you see an event, you know how to use it. With the observer interface, people often implement various registration methods for receiving notifications and connecting the observer .. with events, although as soon as you learn to register and use one (with the + = operator), the rest are the same.
Benefits for Interfaces
I have not many advantages for interfaces. I assume that they force someone to implement all the methods in the interface. But you cannot force someone to correctly implement all of these methods, so I don’t think that this is of great value.
Syntax
Some people don't like how you should declare a delegate type for each event. In addition, standard event handlers in the .Net infrastructure have the following parameters: (object sender, EventArgs arguments). Since the sender does not specify a specific type, you must use it if you want to use it. This is often the case in practice if you are not feeling quite right because you are losing the protection of a static type system. But, if you implement your own events and don’t follow the .Net framework convention, you can use the correct type, so potential downstream casting is not required.
Scott Langham Feb 15 '09 at 12:35 2009-02-15 12:35
source share