Home >Backend Development >PHP Tutorial >Head First-Observer Pattern, headfirst-Observer_PHP Tutorial
What is the Observer Pattern? The Observer pattern defines a one-to-many relationship between objects.
There are subjects (i.e. observers) and observers in the observer pattern. The subject uses a common interface to notify the observer. The subject does not know the details of the observer. It only knows that the observer implements the subject's interface.
The push method in the universal observer mode is more suitable. Below we will write an example of push. The weather station provides an interface. When the weather changes, the data will be notified to each dashboard for display.
<?php //使用接口,类必须实现几个功能注册,删除,通知这几个动作 interface Subject{ public function registerObserver(Observer $o); public function removeObserver(Observer $o); public function notifyObservers(); } interface Observer{ public function update($a,$b,$c); } //各个面板不同将改行为以接口实现 interface DisplayElement{ public function display(); } class Weather implements Subject{ public $observers; public $changed=false; public $a; public $b; public $c; public function __construct(){ $this->observers = array(); } public function registerObserver(Observer $o){ $this->observers[] = $o; } public function removeObserver(Observer $o){ $key = array_search($o,$this->observers); if($key!==false){ unset($this->observers[$key]); } } public function notifyObserver(){ if($this->changed){ foreach($this->observer as $ob){ $ob->update($this->a,$this->b,$this->c); } } } public function setChanged(){ $this->changed = true; } //当数值改变时通知各个观察者 public function measurementsChanged(){ $this->setChanged(); $this->notifyObserver(); } public function setMeasurements($a,$b,$c){ $this->a = $a; $this->b = $b; $this->c = $c; $this->measurementsChanged(); } } class CurrentConditionsDisplay implements Observer, DisplayElement{ public $a; public $b; public $c; public $subject; public function __construct(Subject $weather){ $this->subject = $weather; $this->subject->registerObserver($this); } public function update($a,$b,$c){ $this->a = $a; $this->b = $b; $this->c = $c; $this->display(); } public function display(){ echo $this->a.$this->b.$this->c; } } ?>
We communicate between these objects in a loosely coupled way, so that we can greatly improve efficiency during later maintenance.
Design principles: Find out the changing aspects of the program, and then separate them; programming for interfaces, not implementation; use more combination and less inheritance