Observer pattern: Defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and automatically updated.
Observer class:
1. Abstract theme roles: Theme roles keep all references to the Observer object in a collection, each subject can have as many observers as possible. Abstract topics provide an interface for adding and removing observer objects.
2. Abstract Observer role: Define an interface for all specific observers and update themselves when the subject of the observation changes
3. Specific theme roles: stores the relevant state to the specific observer object, and notifies all registered observers when the internal state of the specific subject has changed. Specific theme roles are usually implemented with a specific subclass.
4. Specific Observer role: Store a specific Subject object, store the associated state, and implement the update interface required by the abstract observer role to keep its state and subject state consistent
Role:
1. Less coupling of observer models
2. Support for Broadcast communications
The
code is as follows:
<?php
//Abstract theme
Interface subject{
Public Function attach ($observer);
Public Function detach ($observer);
Public Function notifyobservers ();
}
//Specific theme
class Concreatesubject implements subject{
private $_observers;
Public Function __construct () {
$this->_observers = Array ();
}
Public Function Attach ($observer) {
Return Array_push ($this->_observers, $observer);
}
Public Function Detach ($observer) {
$index = Array_search ($observer, $this->_observers);
if ($index = = False | |!array_key_exists ($INDEX, $this->_observers)) {
return false;
}
unset ($this->_observer[$index]);
return true;
}
Public Function Notifyobservers () {
if (!is_array ($this->_observers)) {
return false;
}
foreach ($this->_observers as $observer) {
$observer->update ();
}
return true;
}
}
//Abstract observer
Interface observer{
Public Function Update ();
}
//Specific observer
Class Concreteobserver Implement observer{
private $_name;
Public Function __construct ($name) {
$this->_name = $name;
}
Public Function Update () {
Echo ' Observer ', $this->_name. ' has notified<br/> ';
}
}
//Client
class client{
public static function main () {
$subject = new ConcreteSubject ();
//Add first observer
$observer 1 = new Concreteobserver (' Martin ');
$subject->attach ($observer 1);
//Notification
$subject->notifyobservers ();
//Add a second observer
$observer 2 = new Concreteobserver (' Jaky ');
$subject->attach ($observer 2);
//Notification
$subject->notifyobservers ();
//Delete Observer 1
$subject->deatch ($observer 1);
//Notification
$subject->notifyobservers ();
}
}
Client::main ();
?>