观察者模式

<?php


//=======观察者模式========
//php5中提供了 观察者 和被观察者的接口
//登录
//实现观察者接口
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 attach(SPLObserver $observer){
        $this -> observers -> attach($observer);
    }

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

    }

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

    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){
            echo $subject->hobby;
    }
}


$user = new user('taiqiu ');
$user->attach(new secrity());
$user->attach(new ad());
$user->login();

自动调用了安全模块的登录次数 和 广告模块推荐广告

原文地址:https://www.cnblogs.com/long613/p/7682458.html