When many relationship between objects, using the observer pattern. For example, when an object is modified, it is automatically notified dependent objects. The observer pattern belongs to the type of model.
<?php class Subject{ private $observer_list; private $num; public function __construct(){ $this->observer_list = new SplDoublyLinkedList(); } public function attach(Observer $observer){ $this->observer_list->push($observer); } public function setNum($num){ $this->num = $num; $this->notify(); } public function getNum(){ return $this->num; } public function notify(){ foreach ($this->observer_list as $observer) { $observer->update(); } } } abstract class Observer{ public $subj; public function __construct(Subject $subj){ $this->subj = $subj; $this->subj->attach($this); } abstract function update(); } class BinObserver extends Observer{ public function update(){ echo "二进制更新:".decbin($this->subj->getNum())."\n"; } } class OctObserver extends Observer{ public function update(){ echo "八进制更新:".decoct($this->subj->getNum())."\n"; } } class HexObserver the extends the Observer { public function Update () { echo "Hex Update:." dechex ( $ the this -> subj-> getNum ()) "\ the n-." ; } } $subject = new Subject(); new BinObserver($subject); new OctObserver($subject); new HexObserver($subject); $subject->setNum(22);
operation result:
Binary Update: 10110 octal update: 26 hex update: 16
Reproduced in: https: //www.cnblogs.com/itsuibi/p/11058164.html