What is the Observer pattern? The Observer pattern defines a one-to-many relationship between objects.
There are themes (observers) and observers in the observer pattern. The topic uses a common interface to inform the Observer that the subject does not know the details of the observer, only that the observer implements the interface of the subject.
Popular observer patterns in the push of the way more suitable point, below we write a push example, the weather station provides an interface, when the weather changes, the data will be notified to each Kanban display.
<?php//uses interfaces, classes must implement several functions to register, delete, notify these actions interface Subject{public function Registerobserver (Observer $o);p ublic function Removeobserver (Observer $o);p ublic function notifyobservers ();} Interface observer{public function Update ($a, $b, $c);} Different panels will change behavior to interface implementation Interface Displayelement{public function display ();} Class Weather implements Subject{public $observers;p ublic $changed =false;public $a;p ublic $b;p ublic $c;p ublic 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;} Notifies each observer of public function measurementschanged () {$this->setchanged () when the value changes, $this->notifyobserver (); Public functionSetmeasurements ($a, $b, $c) {$this->a = $a; $this->b = $b; $this->c = $c; $this->measurementschanged ();}} Class Currentconditionsdisplay implements Observer, Displayelement{public $a;p ublic $b;p ublic $c;p ublic $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 when we maintain it later.
Design principle: Find out the changes in the program, and then separate it, for the interface programming, not for implementation programming; Multiple combinations, less inheritance
Head first-Observer pattern