This article provides a detailed analysis of the observer mode in php. For more information, see
Observer mode:Defines a one-to-many dependency between objects. When the status of an object changes, all objects dependent on it are notified and automatically updated.
Observer class:
1. Abstract topic role: the topic role stores all references to the observer object in a collection. Each topic can have any number of observers. Abstract topics provide interfaces for adding and deleting observer objects.
2. Abstract observer role: defines an interface for all specific observers and updates themselves when the observed topic changes.
3. Specific topic role: stores the relevant status to a specific observer object. When the internal status of a specific topic changes, a notification is sent to all registered observers. A topic role is usually implemented by a specific subclass.
4. A specific observer role: stores a specific topic object, stores relevant States, and implements the update interface required by the abstract observer role to ensure its own State is consistent with that of the topic.
Purpose:
1. The observer mode has a low coupling degree.
2. Support for Broadcast Communication
The Code is as follows:
// Abstract topic
Interface Subject {
Public function attach ($ observer );
Public function detach ($ observer );
Public function yyobservers ();
}
// Specific topic
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 policyobservers (){
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
';
}
}
// Client
Class Client {
Public static function main (){
$ Subject = new ConcreteSubject ();
// Add the first observer
$ Observer1 = new ConcreteObserver ('martin ');
$ Subject-> attach ($ observer1 );
// Notification
$ Subject-> policyobservers ();
// Adds the second observer.
$ Observer2 = new ConcreteObserver ('jaky ');
$ Subject-> attach ($ observer2 );
// Notification
$ Subject-> policyobservers ();
// Delete observer 1
$ Subject-> deatch ($ observer1 );
// Notification
$ Subject-> policyobservers ();
}
}
Client: main ();
?>