php设计模式-观察者模式

2021-01-17 14:13

阅读:706

标签:highlight   user   lob   observer   观察者   this   undo   subject   次数   

/**
 * 观察对象
 * 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();

  

php设计模式-观察者模式

标签:highlight   user   lob   observer   观察者   this   undo   subject   次数   

原文地址:https://www.cnblogs.com/xiangdongsheng/p/13363852.html


评论


亲,登录后才可以留言!