<? Php/*** Observer mode ** // *** abstract topic role */interface Subject {/*** Add a new observer object * @ param Observer $ observer */public function attach (Observer $ observer ); /*** delete a registered Observer object * @ param observer $ Observer */public function detach (observer $ Observer ); /*** notify all registered observer objects */public function notifyObservers ();}/*** specific topic role */class ConcreteSubject implements Subject {private $ _ observers; public function _ construct () {$ this-> _ observ Ers = array ();}/*** adds a new Observer object * @ param observer $ Observer */public function attach (observer $ Observer) {return array_push ($ this-> _ observers, $ observer );} /*** delete a registered Observer object * @ param observer $ Observer */public function detach (observer $ observer) {$ index = array_search ($ Observer, $ this-> _ observers); if ($ index = FALSE |! Array_key_exists ($ index, $ this-> _ observers) {return FALSE;} unset ($ this-> _ observers [$ index]); return TRUE ;} /*** notify all registered observer objects */public function policyobservers () {if (! Is_array ($ this-> _ observers) {return FALSE;} foreach ($ this-> _ observers as $ observer) {$ observer-> update ();} return TRUE;}/*** abstract Observer role */interface Observer {/*** update Method */public function update ();} class ConcreteObserver implements Observer {/*** Observer name * @ var <type> */private $ _ name; public function _ construct ($ name) {$ this-> _ name = $ name;}/*** update Method */public function update () {echo "Observer ". $ this-> _ na Me. "has notified. \ n ";}}$ subject = new ConcreteSubject ();/* Add the first observer */$ observer1 = new ConcreteObserver ('martin '); $ subject-> attach ($ observer1); echo "\ n The First slave Y: \ n"; $ subject-> policyobservers (); /* add The Second Observer */$ observer2 = new ConcreteObserver ('phppance'); $ subject-> attach ($ observer2); echo "\ n The Second Y: \ n "; $ subject-> policyobservers ();/* Delete the first observer */$ subject-> detach ($ observer1); echo" \ n The Third policy: \ n "; $ subject-> policyobservers ();?>
Go to: http://wend1054.blog.163.com/