Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can an observer observe multiple observables?

trying to find an example of this, it's possible that I am not going the right way around it, or that my mind has over simplified the concept of the observer pattern.

I want to create a class that controls messages from a web service, and I want this class to monitor the changes of many other operations.

The observer pattern examples I have seen demonstrate many observers watching a single observable, can I (or should I) do this the other way round? What else should I be doing?

like image 400
Mild Fuzz Avatar asked Dec 16 '22 17:12

Mild Fuzz


1 Answers

Just register a single Observer instance in many Oservable instances.

You probably will want to pass Observable instance to Observer, whenever Observable updates, so that Observer knows which specific object updated it.

A trivial example:

interface Observer {   
  public update(Observable $observable);
}

class Observable() {
   private $observers = array();

   public function register(Observer $observer) {
     $this->observers[] = $observer;
   }

   public function update() {
     foreach($observers as $observer) {
       $observer->update($this);
     }
   }
}

$observer = new ObserverImplementation();

$observable1->register($observer);
$observable2->register($observer);

$observable1->update();
$observable2->update();

Also you might want to lookup the Mediator pattern.

Here's pretty nice implementation of it: Symfony Event Dispatcher

like image 197
Mchl Avatar answered Dec 28 '22 08:12

Mchl