The observer pattern can be understood, for example, an employee in an office who has a hobby of stocks. and project managers often travel out of the office, so they can do it in addition to working, but in order to avoid seeing the manager back, they need to know when the manager will be back in the office. So they can join the front desk, and if the manager comes back, then the front desk only needs to call one of them, so everyone knows the manager is back. If the manager comes back as a pair of like, each employee as a pair of image. So when the manager returns, the state of the individual employee objects changes as the state changes.
The so-called observer pattern is the definition of a one-to-many dependency between images. So that when the state of an object changes, all the images that depend on it are notified and the state is automatically changed.
Here we can take the boss and staff as an example:
Interface boss{public function attach (observer $observer);p Ublic function detach (observer $observer);p ublic function notifymsg ();} Interface observer{ public function change ();} class secretary implements boss{ private $observers = array (); public function attach (observer $observer) { if (!in_array ($observer, $this->observers)) { $this->observers[]= $observer; } } public function Detach (observer $observer) { if ($index =array_ Search ($observer, $this->observers)) { &nbsP; unset ($this->observers[$index]); } } public function notifymsg () { foreach ($this->observers as $ observer) { $observer- >change (); } }}class observer1 Implements observer{ public function change () { echo ' continue to work! ';}} class observer2 implements observer{ public function Change () { echo ' Go to toilet '; }} $Secretary =new secretary (); $observer 1 =new observer1 (); $observer 2 =new observer2 (); $Secretary->attach ($observer 1); $Secretary Attach ($observer 2); $Secretary->notifymsg ();
This is not the way to apply inheritance, but rather a combination of ways to combine the objects of the observer into the boss theme.
The Observer pattern for PHP design Patterns