Whilst learning events and delegates I can't help but think about the Observer design pattern.
I'm sort of novice level with both C# and design patterns. When using events and delegates to lets say, firing an event from a child form and being picked up by the parent, is that the Observer design pattern?
What other design patters are events and delegates used in?
I'd be interested to know about other 'things' (sorry for my lack of terminology) in .NET are based on common design patterns, such as those from the Gang of Four.
I think it's easier to understand code examples and explanations with such topics if you can relate it to a pattern. Personally anyway.
Thanks.
In software engineering, the delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as inheritance. In delegation, an object handles a request by delegating to a second object (the delegate). The delegate is a helper object, but with the original context.
Delegates can be used to implement the observer pattern - think of events. It wouldn't take much to refactor that into using delegates if you preferred. The only advantage I can think of with implementing an interface is member name consistency across all implementations.
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
A delegate is a way of telling C# which method to call when an event is triggered. For example, if you click a Button on a form, the program would call a specific method. It is this pointer that is a delegate. Delegates are good, as you can notify several methods that an event has occurred, if you wish so.
is that the Observer design pattern?
Yes. Events are basically a langauge-specific implementaiton of the observer design pattern. It was deemed useful enough to build directly into the language in C#.
Many design patterns can be written using delegates in C# - But that's more of an implementation detail than the pattern itself. For example, the visitor pattern and the command pattern can be implemented (quite elegantly) via delegates.
You are correct - events/delegates are indeed an implementation of the Observer pattern.
It has been said that the pattern is a first class citizen of the .NET framework.
Apart from Observer, there is of course Iterator (whenever you use foreach
and IEnumerable
\ IEnumarable<T>
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With