Created
December 11, 2013 01:03
-
-
Save patrioticcow/7903380 to your computer and use it in GitHub Desktop.
Observer Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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