can an observer observe multiple observables?

前端 未结 5 1735
南笙
南笙 2021-02-10 16:14

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

5条回答
  •  遥遥无期
    2021-02-10 16:42

    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

提交回复
热议问题