PHP Implementation Viewer mode

Source: Internet
Author: User

<?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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.