观察者模式

<?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();


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容