使用HBase Shell命令
阿新 • • 發佈:2020-11-22
觀察者模式是一種行為設計模式,允許你定義一種訂閱機制,可在物件(A物件)事件發生時通知多個 ‘觀察者’,即觀察A物件的其他物件。
程式碼示例
注:PHP 中包含幾個內建介面(SplSubject、SplObserver),它們能讓你的觀察器模式實現與其他 PHP 程式碼相容。
<?php class subject implements \SplSubject { public $state; //儲存訂閱者,通知時候遍歷使用 private $observers; public function __construct() {$this->observers = new \SplObjectStorage(); } //新增訂閱物件 public function attach(SplObserver $observer) { // TODO: Implement attach() method. $this->observers->attach($observer); } //刪除訂閱物件 public function detach(SplObserver $observer) {// TODO: Implement detach() method. $this->observers->detach($observer); } //遍歷通知訂閱者 public function notify() { // TODO: Implement notify() method. foreach ($this->observers as $observer){ $observer->update($this); } }//業務邏輯,業務變更時通知關聯業務作出對應變更 public function someBusinessLogic() { //模仿業務變更 $this->state = mt_rand(0,10); //通知訂閱者 $this->notify(); } } //訂閱者A class concreateObserverA implements \SplObserver { public function update(SplSubject $subject) { // TODO: Implement update() method. echo 'A 關聯業務變更'; } } //訂閱者B class concreateObserverB implements \SplObserver { public function update(SplSubject $subject) { // TODO: Implement update() method. echo 'B 關聯業務變更'; } } //客戶端 $subject = new subject(); $conA = new concreateObserverA(); //新增訂閱者A $subject->attach($conA); $conB = new concreateObserverB(); //新增訂閱者B $subject->attach($conB); //業務邏輯變更後,通知訂閱者使訂閱者邏輯變更 $subject->someBusinessLogic();