<?PHP//PHP Design mode Observer Pattern /** The person being observed*/
classUserImplementssplsubject{ Public $lognum; Public $hobby; protected $observers=NULL; Public function__construct ($hobby){ $this->lognum=Rand(1,10); $this->hobby=$hobby; $this->observers=NewSplobjectstorage (); } Public functionLogin () {$this-notify (); } Public functionAttach (Splobserver$observer){ $this->observers->attach ($observer); } Public functionDetach (Splobserver$observer){ $this->observers->detach ($observer); } Public functionNotify () {$this->observers->Rewind(); while($this->observers->valid ()) { $observer=$this->observers-> Current(); $observer->update ($this); $this->observers->Next(); } } } /** * Viewer*/ classSecrityImplementssplobserver{ Public functionUpdate (Splsubject$subject){ if($subject->lognum<3){ Echo' This is the first '.$subject->lognum. ' Secure Login '; }Else{ Echo' This is the first '.$subject->lognum. ' Times Login, Exception '; } } } classAdImplementssplobserver{ Public functionUpdate (Splsubject$subject){ if($subject->hobby== ' Sports '){ Echo' Billiards tickets for the English Championship '; }Else{ Echo' Good study Day day; } } } //Implementation Observations $user=NewUser (' study '); $user->attach (Newsecrity ()); $user->attach (Newad ()); $user-login ();?>
The Observer pattern is a behavior pattern, which defines a one-to-many dependency between objects, so that when an object's state changes, all objects that depend on it are notified and refreshed automatically. It perfectly separates the observer object from the object being observed. You can maintain a list of dependencies (observers) that are of interest to the principal in a stand-alone object (body). Let all observers implement a common Observer interface to remove the direct dependencies between the principal and the dependent objects.
PHP Implementation Viewer mode