1

In observer pattern Observer notifies listeners usually by invoking on each some method like:

OnSomethingUpdated(Object) {
....

In this case we have coupling: Observer should do some operation with each listener. When I would like modify Observer or Listener by inheritance or try to extract abstract superclass for simplify logic of Observer (or Listener) it getting difficult propagate messages, I receive spaghetti code. I think that should exists some way of decoupling business logic of work of Observer from logic of propagating messages to listeners. May be better contrary - listeners should check some pool of messages. Does exist similar pattern? Thanks.

Charles
  • 50,943
  • 13
  • 104
  • 142
user710818
  • 23,228
  • 58
  • 149
  • 207

4 Answers4

3

The listener should actually be an interface:

interface MyListener {
  void onSomethingUpdated(Object eventData);
}

This way, the subject is decoupled from the concrete instances of its observers; It should keep a list of these interface references.

Take a look here for how to implement this pattern in Java.

Now, to further decouple the subject from the message propagation, I suggest you take a look at the mediator pattern.

Jordão
  • 55,340
  • 13
  • 112
  • 144
1

In the observer pattern, an Observer registers with an Observable subject. The onSomethingUpdated() method of the Observer is invoked by the Observable, which notifies all loosely-coupled listeners. There's a related example here.

observer pattern

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

You're probably not going to like this answer very much, but I'll say it anyway: inheritance is not for code reuse. The observer pattern should not lead to tight coupling -- it should lead to decoupling! So if you're ending up with spaghetti code around your observers/listeners when you're extracting abstract base classes or subclassing, it's because you shouldn't be using inheritance.

There, I said it.

mergeconflict
  • 8,156
  • 34
  • 63
0

You could add a Business Delegate in between or a simple Facade.

So the Observer will only receive the Notification and then delegate the implementation to actual object that contains the Business Logic. This way you are free to make changes to your Business Logic class as you like.

Padmarag
  • 7,067
  • 1
  • 25
  • 29