<?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();
网友评论