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.