Php design pattern-Observer Pattern

Source: Internet
Author: User

<? Php/*** observer **/class Subject implements SplSubject {protected $ _ value; protected $ _ observers; /*** constructor ** @ return void */public function _ construct () {$ this-> _ observers = new SplObjectStorage ();} /*** append the observer * @ see SplSubject: attach () */public function attach (SplObserver $ observer) {$ this-> _ observers-> attach ($ observer);}/*** discard observer * @ see SplSubject: detach () */public function detach (SplObserver $ observer) {$ this-> _ observers-> detach ($ observer);}/*** notify the observer * @ see SplSubject :: every y () */public function every Y () {foreach ($ this-> _ observers as $ observer) {$ observer-> update ($ this );}} /*** set the latest value ** @ param mixed $ value * @ return */public function setValue ($ value) {$ this-> _ value = $ value; $ this-> Y ();}/*** get the last updated value ** @ return mixed */public function getValue () {return $ this-> _ value ;}/ *** Observer **/class Observer implements SplObserver {/\ *** @ see SplObserver: update () */public function update (SplSubject $ subject) {echo 'I know you '. $ subject-> getValue () ;}} header ('content-type: text/html; charset = UTF-8 '); date_default_timezone_set ('Asia/Shanghai '); error_reporting (E_ALL); $ subject = new Subject (); $ observer = new Observer (); $ subject-> attach ($ observer ); $ subject-> setValue ('updated ');

 

This article is from the "phper" blog, please be sure to keep this source http://janephp.blog.51cto.com/4439680/1286698

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.