Introduction
The observer pattern defines one-to-many dependencies of objects, so that when an object changes state, all its dependents will be notified and automatically updated!
Design principles
In the observer In mode, what changes is the status of the subject and the number of observers. Using this pattern, you can change objects that depend on the theme's state without changing the theme. ——Find out the changing aspects of the program, and then separate them from the fixed aspects!
Both the subject and the observer use interfaces: the observer uses the subject's interface to register with the subject, and the subject uses the observer interface Notify observers. This allows the two to operate normally while having the advantage of loose coupling! ——For interface programming, not implementation programming!
.
The observer pattern uses "composition" to combine many observers into a theme. This relationship between objects (observers - subjects) is not generated through inheritance, but through composition at runtime. ——Use more combination and less inheritance!
Code
Copy code The code is as follows:
/**
* Observer Pattern
* @author: Mac
* @date: 2012/02/22
* /
class Paper{ /* Topic*/
private $_observers = array();
public function register($sub){ /* Register observers*/
$this->_observers [] = $sub;
}
public function trigger(){ /* External unified 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 "Callbackn";
}
}
//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, it only needs to be registered in the subject (also called an observable) (there are many ways to register, you can also do it during construction , or register in the interface accessed by the framework), and then implement the code directly in the interface of the new object. This reduces the coupling between subject and observer objects.
Good design patterns don’t go directly into your code, they go into your brain.
http://www.bkjia.com/PHPjc/325135.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325135.htmlTechArticleIntroduces the observer pattern to define one-to-many dependencies of objects, so that when an object changes state, it All dependencies will be notified and automatically updated! The design principle is in the observer module...