Php design pattern-Observer pattern, php design pattern observer
In web applications, some small-scale data and business changes usually require changes to other related business data. In this case, the observer mode is suitable.
The Observer mode is usually implemented by using an interface called Observer. If other classes want to introduce the Observer, this interface must be implemented.
For example, if the exchange rate of a product changes, the display information and price calculation of all product pages also change.
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 public function setExchangeRate ($ new_rate) {28 $ this-> exchange_rate = $ new_rate; 29 // The exchange rate changes, notifying all observers 30 $ this-> yyobservers (); 31} 32 33 public function registerObservers ($ obj) {34 $ this-> observers [] = $ obj; 35} 36 37 public function policyobservers () {38 foreach ($ this-> observers as $ observer) {39 // notify the observer 40 $ Observer-> notify ($ this); 41} 42} 43} 44 45 class ProductItem implements observer {46 public function _ construct () {47 // register as the observer for the exchange rate 48 ExchangeRate: getInstance ()-> registerObservers ($ this); 49} 50 public function notify ($ obj) {51 if ($ obj instanceof ExchangeRate) {52 echo "Please update the product exchange rate ". PHP_EOL; 53} 54} 55} 56 57 $ p1 = new ProductItem (); 58 $ p2 = new ProductItem (); 59 60 ExchangeRate: getInstance () -> setExchangeRate (6.2 );