Php design pattern-Observer pattern, php design pattern observer

Source: Internet
Author: User

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 );

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.