观察者模式

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


你可能感兴趣的:(观察者模式)