Skip to content

Instantly share code, notes, and snippets.

@patrioticcow
Created December 11, 2013 01:03
Show Gist options
  • Save patrioticcow/7903380 to your computer and use it in GitHub Desktop.
Save patrioticcow/7903380 to your computer and use it in GitHub Desktop.
Observer Pattern
interface Observer {
function notify($obj);
}
class ExchangeRate {
static private $instance = NULL;
private $observers = array();
private $exchange_rate;
private function ExchangeRate() {
}
static public function getInstance() {
if (self::$instance == NULL) {
self::$instance = new ExchangeRate();
}
return self::$instance;
}
public function getExchangeRate() {
return $this->$exchange_rate;
}
public function setExchangeRate($new_rate) {
$this->$exchange_rate = $new_rate;
$this->notifyObservers();
}
public function registerObserver($obj) {
$this->observers[] = $obj;
}
function notifyObservers() {
foreach($this->observers as $obj) {
$obj->notify($this);
}
}
}
class ProductItem implements Observer {
public function __construct() {
ExchangeRate::getInstance()->registerObserver($this);
}
public function notify($obj) {
if ($obj instanceof ExchangeRate) {
// Update exchange rate data
print "Received update!\n";
}
}
}
$product1 = new ProductItem();
$product2 = new ProductItem();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment