观察者模式

<?php
//观察者模式
class User implements SplSubject{
    public $lognum;
    public $hobby;

    protected $observers = null;
    public function __construct($hobby){
        $this->lognum = rand(1,10);
        $this->hobby = $hobby;
        $this->observers = new SplObjectStorage();
    }

    public function login(){
        $this->notify();
    }

    public function attach(SPLObserver $observer){
        $this->observers->attach($observer);
    }

    public function detach(SPLObserver $observer){
        $this->observers->detach($observer);
    }

    public function notify(){
        $this->observers->rewind();
        while($this->observers->valid()){
            $observer = $this->observers->current();
            $observer->update($this);
            $this->observers->next();
        }
    }
}

class Secrity implements SPLObserver{
    public function update(SplSubject $subject){
        if($subject->lognum <= 3){
            echo '这是第'.$subject->lognum . '次安全登陆';
        }else{
            echo '这是第'.$subject->lognum . '次登陆,异常';
        }
    }
}

class Ad implements SPLObserver{
    public function update(SplSubject $subject){
        if($subject->hobby == 'sports'){
            echo '台球英锦赛门票预订';
        }else{
            echo '好好学习天天向上';
        }
    }
}

$user = new User('sports');
$user->attach(new Secrity());
$user->attach(new Ad());

$user->login();
posted @ 2019-05-29 14:56  zhang-san  阅读(189)  评论(0编辑  收藏  举报