在web应用中,通常,一些小范围的数据和业务的改变,其他相关的业务数据也需要发生改变,这种情况,观察者模式很适合。
观察者模式,通常是通过使用一个叫Observer的接口实现的,如果其他的类要引入观察者,就要实现这个接口
比如,有一个这样的需求,如果产品汇率改变了,所有产品的相关页面展示信息和价格计算也跟着改变
1 interface Observer { 2 function notify( $obj ); 3 } 4 5 class ExchangeRate { 6 static private $instance = NULL; 7 private $observers = array(); 8 private $exchange_rate; 9 10 private function __construct(){11 }12 13 private function __clone(){14 }15 16 public static function getInstance(){17 if( self::$instance == NULL ) {18 self::$instance = new ExchangeRate();19 }20 return self::$instance;21 }22 23 public function getExchangeRate(){24 return $this->exchange_rate;25 }26 27 public function setExchangeRate( $new_rate ){28 $this->exchange_rate = $new_rate;29 //汇率改变,通知所有观察者30 $this->notifyObservers();31 }32 33 public function registerObservers( $obj ){34 $this->observers[] = $obj;35 }36 37 public function notifyObservers(){38 foreach( $this->observers as $observer ) {39 //通知观察者40 $observer->notify( $this );41 }42 }43 }44 45 class ProductItem implements Observer {46 public function __construct(){47 //注册成为汇率的观察者48 ExchangeRate::getInstance()->registerObservers( $this );49 }50 public function notify( $obj ){51 if( $obj instanceof ExchangeRate ) {52 echo "请更新产品的汇率" . PHP_EOL;53 }54 }55 }56 57 $p1 = new ProductItem();58 $p2 = new ProductItem();59 60 ExchangeRate::getInstance()->setExchangeRate( 6.2 );