0

I know that objects that are registered to receive callback messages are often named as listeners (as in PaintListener, PropertyListener) or observers (as in ScopeObserver, TileObserver).

I also know both are, usually, implementations of the GoF Observer pattern.

My question is: when naming a class, is there any conceptual difference between calling it MyListener and MyObserver?

EDIT: the suggested question referenced as a duplicate of this one indeed addresses the same question, but none of the answers clarifies it for me. Not even the chosen one.

I don't want to know whether Listeners can be seen as being Observers GoF implementations. I want to know if there's any semantical reasoning when choosing one name or the other.

A comment on the original question, which I understand was posted as a joke, sounds just like what I expected the answer to be: "In the former one code watches the other code for movement, while in latter one code listens to the other code for any noise."

Mario Marinato
  • 4,561
  • 3
  • 29
  • 49
  • 1
    Possible duplicate of [Observer Design Pattern vs "Listeners"](http://stackoverflow.com/questions/3358622/observer-design-pattern-vs-listeners) – jaco0646 May 31 '16 at 19:23

1 Answers1

2

Remember this is a subjective point of view.

English is not my primary language, but both terms give me the same idea of actively watching things which can be perceived.

However, for humans at least (I may be influenced by my primary language), we tend to observe something specific, while we usually listen to everything unless we concentrate well.

Applied to OOP, my thought on it is that these terms are likely to be interchangeables. However, I would prefer the term "Observer" to name an object watching specifically a given/known set of objects, and "Listener" to name an object which does not have the knowledge of its targets.

To illustrate this more technically:

  • Observer: the Mouse watches one (or more) Cat. The Mouse is a cat-Observer which knows all the cats of the neighbourhood.
  • Listener: the Mouse watches for an event cat_in_sight to occur. The Mouse is a cat-Observer's Observer, and does not know all the cats which may fire this event.

This way, this listener have less responsibilities thanks to an intermediate layer (in this case an Eventclass maybe). We could also imagine giving this responsibility to the cat:

  • Listener: the Cat knows all the mouses in the neighbourhood and informs them whenever it comes near. A Mouse is a cat-Listener, as it does not know the cats (-> the cats "register" the mouses themselves).

However the cats (observed) have more responsibilities in this case.

I am not sure if I was clear enough, I hope it helped. :-)

GnxR
  • 829
  • 1
  • 8
  • 20