: This article mainly introduces the HeadFirst-Observer Mode. if you are interested in the PHP Tutorial, refer to it. What is the observer mode? The observer mode defines the one-to-many relationship between objects.
The observer mode includes the topic (the observer can be observed) and The Observer. A topic uses a common interface to notify the observer. the topic does not know the details of the observer, but only the observer implements the topic interface.
The push method in the common observer mode is more suitable. let's write an example. the weather station provides an interface. when the weather changes, the data is notified to each dashboard.
Observers = array ();} public function registerObserver (Observer $ o) {$ this-> observers [] = $ o;} public function removeObserver (Observer $ o) {$ key = array_search ($ o, $ this-> observers); if ($ key! = False) {unset ($ this-> observers [$ key]) ;}} public function policyobserver () {if ($ this-> changed) {foreach ($ this-> observer as $ ob) {$ ob-> update ($ this-> a, $ this-> B, $ this-> c) ;}} public function setChanged () {$ this-> changed = true;} // notify each observer of public function measurementsChanged () when the value changes () {$ this-> setChanged (); $ this-> policyobserver ();} public function setMeasurements ($ a, $ B, $ c) {$ this-> a = $ a; $ this-> B = $ B; $ this-> c = $ c; $ This-> measurementsChanged () ;}} class CurrentConditionsDisplay implements Observer, DisplayElement {public $ a; public $ B; public $ c; public $ subject; public function _ construct (Subject $ weather) {$ this-> subject = $ weather; $ this-> subject-> registerObserver ($ this );} public function update ($ a, $ B, $ c) {$ this-> a = $ a; $ this-> B = $ B; $ this-> c = $ c; $ this-> display ();} public function display () {echo $ this->. $ this-> B. $ This-> c ;}}?>
We use loose coupling to communicate these objects, so that we can greatly improve the efficiency during later maintenance.
Design principle: find out the changing aspects of the program, and then separate it; for interface programming, not for implementation programming; multi-purpose combination, less inheritance
The above introduces the Head First-observer mode, including some content, and hopes to help friends who are interested in PHP tutorials.