Well, there are thousands more. Let us
implement this pattern.
Observer::notify ()
Email Notifier
For each
observer
IM Notifier
Observable
Chapter 4
[ 85 ]
Our entire observer objects implement observer interface as shown below:
interface observer
{
public function notify();
}
?>
Now some observer objects, which we will notify when the state of an observable
object changes:
class YMNotifier implements observer
{
public function notify()
{
//send alerts using YM
echo "Notifying via YM\n";
}
};
?>
Another notifier:
class EmailNotifier implements observer
{
public function notify()
{
//send alerts using Email
echo "Notifying via Email\n";
}
};
?>
Now we need to create our observer.
class observable
{
private $observers = array();
public function register($object)
{
if ($object instanceof observer )
$this->observers[] =$object;
else
echo "The object must implement observer interface\n";
}
Design Patterns
[ 86 ]
public function stateChange()
{
foreach ($this->observers as $observer)
{
$observer->notify();
}
}
}
?>
Now let us use it:
$postmonitor = new observable();
$ym = new YMNotifier();
$em = new EmailNotifier();
$s= new stdClass();
$postmonitor->register($ym);
$postmonitor->register($em);
$postmonitor->register($s);
$postmonitor->stateChange();
?>
The output is as follows:
The object must implement observer interface
Notifying via YM
Notifying via Email
Proxy Pattern or Lazy Loading
Another very important programming practice in OOP is lazy loading and loose
coupling.
Pages:
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105