美文网首页
观察者模式

观察者模式

作者: 鸿雁长飞光不度 | 来源:发表于2020-04-09 10:26 被阅读0次

    1.观察者模式

    PHP内置的类提供了对SPL的原生支持,实现如下。

    class ConcreteSubject implements SplSubject
    {
        private $observers;
        private $data;
    
        public function __construct()
        {
            $this->observers = new SplObjectStorage();
        }
        
        public function attach(SplObserver $observer)
        {
            $this->observers->attach($observer);
        }
    
        public function notify()
        {
           foreach ($this->observers as $observer) {
               $observer->update($this);
           }
        }
    
        public function detach(SplObserver $observer)
        {
            $this->observers->detach($observer);
        }
    
        public function setData($dataNow){
            $this->data = $dataNow;
        }
    
        public function getData(){
            return $this->data;
        }
    }
    
    class ConcreteObserver implements SplObserver {
    
        public function update(SplSubject $subject)
        {
            echo $subject->getData();
        }
    }
    
    class Client
    {
        public function __construct()
        {
            echo "create three new concrete observers,a new concrete subject:";
            $ob1 = new ConcreteObserver();
            $ob2 = new ConcreteObserver();
            $ob3 = new ConcreteObserver();
            $subject = new ConcreteSubject();
            $subject->setObservers();
            $subject->setData("here is your data\n");
            $subject->attach($ob1);
            $subject->attach($ob2);
            $subject->attach($ob3);
            $subject->notify();
            $subject->detach($ob3);
            $subject->notify();
        }
    }
    $worker = new Client();
    
    image.png

    相关文章

      网友评论

          本文标题:观察者模式

          本文链接:https://www.haomeiwen.com/subject/ileeuftx.html