Design mode php instance: Observer Mode
When the state of an object changes, it will affect the changes of other objects. in this case, the Observer Mode can be used. In an application such as wordpress, it allows external developers to develop plug-ins, such as user-authorized blog statistics plug-ins and point plug-ins. in this case, you can use the observer mode to register these plug-ins first, after a user publishes a blog post, the corresponding plug-in update is automatically notified. The observer mode conforms to the interface isolation principle and achieves loose coupling between objects. Observer Mode UML diagram: the SplSubject and SqlOberver interfaces [php] view plain copyinterface SplSubject {function attach (SplObserver $ observer) and function detach (SplObserver $ observer) are provided in php SPL ); function Y ();} interface SqlObserver {function update (SplSubject $ subject);} The following is an example [php] view plain copyclass Subject implements SplSubject {private $ observers; public function attach (SplObserver $ observer) {if (! In_array ($ observer, $ this-> observers) {$ this-> observers [] = $ observer ;}} public function detach (SplObserver $ observer) {if (false! = ($ Index = array_search ($ observer, $ this-> observers) {unset ($ this-> observers [$ index]);} public function post () {// post related code $ this-> Policy ();} private function using Y () {foreach ($ this-> observers as $ observer) {$ observer-> update ($ this) ;}} public function setCount ($ count) {echo "data volume plus ". $ count;} public function setIntegral ($ integral) {echo "add points ". $ integral ;}} class Observer1 implements SplObserver {public function update ($ subject) {$ subject-> setCount (1 );}} class Observer2 implements SplObserver {public function update ($ subject) {$ subject-> setIntegral (10) ;}} class Client {public function test () {$ subject = new Subject (); $ subject-> attach (new Observer1 (); $ subject-> attach (new Observer2 ()); $ subject-> post (); // output: data volume plus 1 point plus 10 }}