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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With