Introduction

The Observer pattern is like a newspaper subscription. You have a subject, which is the object that changes its state (in our example is the newspaper) and a observer, which is the object that receives these changes (the subscriber).

Implementing the Observer Pattern

First I'll create the subject interface.

interface Subject {
	public function registerObserver(Observer $o);
	public function removeObserver(Observer $o);
	public function notifyObservers();
}
Now I'll create the observer interface.

interface Observer {
	public function update($news);
}
Now I'll create the Newspaper class which implements the Subject interface.

class Newspaper implements Subject {
	private $observers = array();
	private $news;
 
	public function __construct() {
	}
 
	public function registerObserver(Observer $o) {
		$this->observers[] = $o;
	}
 
	public function removeObserver(Observer $o) {
		uns
1000
et($this->observers[array_search($o, $this->observers)]);
	}
 
	public function notifyObservers()
1000
 {
		foreach($this->observers as $observer) {
			$observer->update($this->news);
		}
	}
 
	public function setNewNews($news) {
		$this->news = $news;
		$this->notifyObservers();
	}
}
Now the Subscriber class which implements the Observer interface.

class Subscriber implements Observer {
	private $newspaper;
 
	public function __construct(Subject $newspaper) {
		$this->newspaper = $newspaper;
		$this->newspaper->registerObserver($this
1000
);
	}
 
	public function cancelSubscript() {
		$this->newspaper->removeObserver($this);
	}
 
	public function update($news) {
		echo date("h:i:s") . ": " . $news;
	}
}
And finally I'll use all of this.

$newspaper = new Newspaper();
$subscriber1 = new Subscriber($newspaper);
$subscriber2 = new Subscriber($newspaper);
$newspaper->setNewNews("Today is tuesday.");
$newspaper->setNewNews("So, tomorrow will be wednesday.");
$subscriber1->cancelSubscript();
$newspaper->setNewNews("So, the day after tomorrow will be thursday.");

Conclusion

You can put another classes that implements Observer and all of them will receive the last news!

 
observer.txt · Last modified: 2010/05/18 02:07 by mfacenet
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki