27

我目前正在学习有关设计模式的课程,并且想知道 an 是否EventListenerObservable

我真的看不出它们之间有什么区别,因为它们都有一个订阅者列表,并在某些事情发生变化时通知这些订阅者。

4

4 回答 4

36

AnObservable只是一个对象,您可以在其中观察它的动作。所以任何你可以听到一个动作然后被告知动作发生的地方都是一个Observable.

这意味着事件侦听器就是其中之一。因为您可以收听事件,并且事件会立即通知您它们已经发生。

就个人而言,当有人说Observable我认为事件。这是我关于什么是 observables 的千篇一律的例子。一个类似的例子是发布-订阅系统,它只是不同名称的事件(它确实有细微的不同用例)。

于 2011-05-09T19:58:38.600 回答
22

To my experience, an Event Listener pattern is a different thing from Observer Design Pattern. It is not just a different name or which is part of which.

I have to talk about this concretely. For example, this page gives a c# implementation of an event listener system. In this system, a listener registers its event handling function with a singleton class Events and claims that it can handle a particular type of event. Events maintains a dictionary to map each type of event to its handler function. On the other hand, any class that wants to trigger the event needs to do so through the singleton's function Events.instance.Raise().

Here we can see 3 differences:

Firstly the purpose of the two patterns are different: Listener Design Pattern is to decouple the event detection/raising code from the event handling code, so that when changing or adding new events handling codes, it does not affect other events handling codes; Observer Design Pattern is to make some objects to follow the changes of another object.

The data structure is also different. In Listener Design Pattern, there is only one global dictionary to map each type of event to its handling method. This mapping is 1-to-1. While in Observer Pattern, every observed subject maintains a list of observers. This mapping is 1-to-many: one subject to many observers. There can be multiple instances of such 1-to-many subject-observers relationships.

The behavior is different. In Listener Design Pattern, when a event happens, the event raiser notifies a global mediator (the singleton Events.instance), because it has no information about the event handlers. While in Observer Pattern, when any change happens, the observed subject directly notifies all the observers.

于 2014-09-08T20:59:00.323 回答
3

通过查看 JDK 的源代码,我自己也做了一些更多的研究。我认为它们之间的唯一区别是 anObservable在添加时使用 synchronizedObservers而 anEventListener不使用(至少AbstractButton's 没有)。

于 2011-05-17T18:03:00.883 回答
1

是的,您在其中为特定事件注册侦听器的事件队列似乎是观察者模式的一个示例。

于 2011-05-09T19:59:11.497 回答