The observer mode defines the one-to-many dependency of an object. in this way, when an object changes its status, all its dependent persons will receive notifications and update them automatically! Introduction
The observer mode defines the one-to-many dependency of an object. in this way, when an object changes its status, all its dependent persons will receive notifications and update them automatically!
Design principles
In the Observer Mode, the state of the topic and the number of observers are changed. In this mode, you can change objects dependent on the topic state without changing the topic. -- Find out the changing aspects in the program, and then separate them from the fixed ones!
Both the topic and the Observer use interfaces: The Observer uses the topic interface to register with the topic, and the topic uses the observer interface to notify the observer. This allows the two to operate normally and has the advantage of loose coupling! -- For interface programming, not for implementation programming!
.
Observer Mode uses "combination" to combine many observers into the topic. This relationship between objects (observer-topic) is not generated by inheritance, but by using combinations at runtime. -- Multi-purpose combination, less inheritance!
Code
The code is as follows:
/**
* Observer Mode
* @ Author: Mac
* @ Date: 2012/02/22
*/
Class Paper {/* topic */
Private $ _ observers = array ();
Public function register ($ sub) {/* register an observer */
$ This-> _ observers [] = $ sub;
}
Public function trigger () {/* unified external access */
If (! Empty ($ this-> _ observers )){
Foreach ($ this-> _ observers as $ observer ){
$ Observer-> update ();
}
}
}
}
/**
* The interface to be implemented by the Observer
*/
Interface Observerable {
Public function update ();
}
Class Subscriber implements Observerable {
Public function update (){
Echo "Callback \ n ";
}
}
// The following is the test code.
?
/* Test */
$ Paper = new Paper ();
$ Paper-> register (new Subscriber ());
// $ Paper-> register (new Subscriber1 ());
// $ Paper-> register (new Subscriber2 ());
$ Paper-> trigger ();
Summary
When a new object is to be filled in, you only need to register it in the topic (also called the observer) (there are many registration methods, you can also construct, or register in the interface accessed by the framework), and then implement code directly in the interface of the new object. This reduces the coupling between the subject object and the observer object.
A good design pattern does not directly go into your code, but into your brain.