码迷,mamicode.com
首页 > Web开发 > 详细

php实现观察者模式

时间:2014-09-18 23:55:15      阅读:398      评论:0      收藏:0      [点我收藏+]

标签:io   ar   for   sp   cti   on   c   new   r   

<meta charset=‘utf-8‘ />
<title>观察者模式</title>
<?php
    class Tongzhi implements SPLSubject
    {
        protected $subs = array();
        public $username = ‘我是被观察者‘;

        public function __construct(){
        }
        
        public function attach(SPLObserver $sub){
            $this->subs[] = $sub;
        }

        public function detach(SPLObserver $sub){
            $keys = array_keys($this->subs,$sub);
            $key = $keys[0];
            unset($this->subs[$key]);
        }

        public function notify(){
            foreach ($this->subs as $value) 
            {
                $value->update($this);
            }
        }
    }

    class Obs1 implements SPLObserver
    {
        public function update(SPLSubject $tz){
            echo $tz->username.‘,我是观察者1<br />‘;
        }
    }

    class Obs2 implements SPLObserver
    {
        public function update(SPLSubject $tz){
            echo $tz->username.‘,我是观察者2<br />‘;
        }
    }

    class Obs3 implements SPLObserver
    {
        public function update(SPLSubject $tz){
            echo $tz->username.‘,我是观察者3<br />‘;
        }
    }

    $tz = new Tongzhi;
    $tz->attach(new Obs1);
    $tz->attach(new Obs2);
    $tz->detach(new Obs2);
    $tz->attach(new Obs3);
    $tz->notify();
?>



php实现观察者模式

标签:io   ar   for   sp   cti   on   c   new   r   

原文地址:http://my.oschina.net/u/946060/blog/315828

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!