How is the Observer pattern different from an Event driven model?

拈花ヽ惹草 提交于 2019-12-03 05:06:21

问题


I am a senior level developer but I haven't had a lot of formal training and I although I have used many design patterns and seen them used in my years as a developer, no one really went out of their way to say. "Oh this is an observer pattern, or this is a Singleton pattern."

Reading over some of the design patterns, I came across the Observer pattern and it seems to be to be very similar to the way the .NET framework events work. Am I missing something fundamental about this?


回答1:


The .NET Event model is pretty much a integrated implementation of the observer pattern in the common language runtime. The .NET languages implement observer directly in their language specific manner, using the framework's built-in support for this.

In most programming languages, the observer pattern requires customized development or libraries.

It comes for free as part of the language in C#, VB.NET and most other languages built to use the CLR.




回答2:


From MSDN

Those of you with passing familiarity of the types exposed in the FCL will note that no IObserver, IObservable, or ObservableImpl types are present in the Framework. The primary reason for their absence is the fact that the CLR makes them obsolete after a fashion. Although you can certainly use these constructs in a .NET application, the introduction of delegates and events provides a new and powerful means of implementing the Observer pattern without developing specific types dedicated to support this pattern. In fact, as delegates and events are first class members of the CLR, the foundation of this pattern is incorporated into the very core of the .NET Framework. As such, the FCL makes extensive use of the Observer pattern throughout its structure.




回答3:


Many event models, like the Java 1.1 and beyond, as well as the .NET event model are basically implementations of the Observer pattern.

Note that this even applies to older mechanisms, such as using callback methods in C for event handling. It's the same intent, just implemented slightly differently.




回答4:


Why do you think there must be a difference?

Don't you think the .NET designers read Design Patterns as well?

Actually, the Observer pattern (like all in the book) were well known long before they were categorized and named by the Gof4. It was used to implement the .Net event model, as well as the Win32 & Win16 event models, and probably many others.



来源:https://stackoverflow.com/questions/807778/how-is-the-observer-pattern-different-from-an-event-driven-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!