美文网首页
观察者模式

观察者模式

作者: 初秋夏末 | 来源:发表于2017-11-06 17:28 被阅读9次
    <?php
    
    class ExchangeRate implements SplSubject
    {
        private static $instance = null;
        private $observers = [];
        private $exchange_rate;
    
        private function __construct()
        {
        }
    
        public static function getInstance()
        {
            if (self::$instance == null) {
                self::$instance = new self();
            }
            return self::$instance;
        }
    
        public function getExchangeRate()
        {
            return $this->exchange_rate;
        }
    
        public function setExchangeRate($exchange_rate)
        {
            $this->exchange_rate = $exchange_rate;
            $this->notify();
        }
    
        public function attach(SplObserver $observer)
        {
            $this->observers[] = $observer;
        }
    
        public function detach(SplObserver $observer)
        {
            $this->observers->detach($observer);
        }
    
        public function notify()
        {
            foreach ($this->observers as $observer) {
                $observer->update($this);
            }
        }
    
    }
    
    class ProductItem implements SplObserver
    {
        public function __construct()
        {
            ExchangeRate::getInstance()->attach($this);
        }
    
        public function update(SplSubject $subject)
        {
            if ($subject instanceof ExchangeRate) {
                print "Received update!\n";
            }
        }
    
    }
    
    $product1 = new ProductItem();
    $product2 = new ProductItem();
    
    
    

    相关文章

      网友评论

          本文标题:观察者模式

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