Bastian
Bastian

Reputation: 1593

Relationship in Observer Pattern

Does the observer pattern model a one-to-many relationship or a many-to-many?

I've found many resources where the relationship modeled by the observer pattern is one-to-many. This makes perfectly sense, but isn't it possible to also model a many-to-many relationship and wouldn't it imply that it's general relationship is n:m?

This is a general question about the relationship modeled by the observer pattern and not one about how to add observables as observers to other observables.

Upvotes: 0

Views: 632

Answers (2)

Wolf
Wolf

Reputation: 121

One observed object can have many objects which are registering and waiting to be notified from observer. As you already know, this is one to many. I am not exactly sure how want to make this many to many? Of course you can have the same observers being subscribed to other observable objects, but this doesn't make this pattern many to many IMHO.

Observable1.Subscribe(observer1);
Observable1.Subscribe(observer2);
Observable1.Subscribe(observer3);

Observable2.Subscribe(observer1);
Observable2.Subscribe(observer2);
Observable2.Subscribe(observer3);

...

ObservableN.Subscribe(observer1);
ObservableN.Subscribe(observer2);
ObservableN.Subscribe(observerN);

You just implemented N observer patterns here.

Upvotes: 1

Jonathan Oron
Jonathan Oron

Reputation: 34

To answer your question formally:
http://sourcemaking.com/design_patterns/observer - Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

I would combine the Iterator pattern and iterate over multiple Observers.
To me it makes sense to keep the Observer pattern a one-to-many. Manage your multitude of subscriptions in a different piece of code. That will make it easier to manage your code if your Subjects change.

Upvotes: 1

Related Questions