php设计模式-观察者模式

/**
 * 观察对象
 * Undocumented class
 */
class User implements SplSubject
{
    public $loginCnt;

    private $observers;

    public function __construct()
    {
        $this->observers = new SplObjectStorage;
    }

    public function login()
    { 
        $this->loginCnt = rand(1,30);
        $this->notify();
    }

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

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

    public function notify()
    {
        foreach($this->observers as $observer) {
            $observer->update($this);
        }
    }
}

/**
 * 观察者
 * Undocumented class
 */
class Security implements SplObserver
{
    public function update(SplSubject $subject)
    {
        if ($subject->loginCnt > 10) {
            echo '登录次数过多';
        } else {
            echo '登录正常';
        }
    }
}

$user = new User();
$user->attach(new Security());
$user->login();

  

posted @ 2020-07-22 23:28  coder_xds  阅读(155)  评论(0编辑  收藏  举报