Friday, June 27, 2008

An unorthodox implementation of Observer pattern

This is how py-notify describes itself. And it really is. Most observer implementations I've seen look almost like the good old Observer Pattern from GoF. Although it does the job, it could achieve more loose coupling with some changes. The unorthodox in py-notify is that the events (signals) are not typed. You don't need to pass constants like 'onSomeEvent' around or more worse event objects (but you can do both). Also unorthodox is that you don't need any interfaces for the observers since it's possible to register every method or function. This makes the implementation less verbose and type safe, but much more flexible and easier to implement.
Py-notify has much more to offer on top of the signals concept, but I'm currently only interested in the pure observer concept and partially ported it to php. code/examples

Here is an simple Observer example:

class Observer {
function notify($msg) {
echo "Subject says: $msg\n";
}
}

class Subject {
/**
* @var ekn_Signal
*/
protected $signal;

function __construct() {
$this->signal = new ekn_Signal();
}

function addObserver($observer, $method = 'notify') {
$this->signal->connect(array($observer, $method));
}

function saySomething() {
$this->signal->emit('something');
}

}

$subject = new Subject();
$subject->addObserver(new Observer());
$subject->saySomething();

No comments: