Sunday 26 June 2016

Observer Design pattern

Observer means that someone is looking at your activity, and it may be possible that the observer takes some action depending on your activity. The same concept is applicable to  design pattern as well. We should implement this pattern when we have a one-to-many dependency between our object and one object needs to be changed/notified when any changes are made to any other object.
interface IObserver { function onChanged( $sender, $args ); } interface IObservable { function addObserver( $observer ); } class UserList implements IObservable { private $_observers = array(); public function addCustomer( $name ) { foreach( $this->_observers as $obs ){ $obs->onChanged( $this, $name ); } public function addObserver( $observer ) { $this->_observers []= $observer; } } class UserListLogger implements IObserver { public function onChanged( $sender, $args ) { echo( "'$args' added to user list\n" ); } }
$ul = new UserList(); $ul->addObserver( new UserListLogger() ); $ul->addCustomer( "vivek" ); ?>

No comments:

Post a Comment