The Observer pattern defines a one-to-many dependency on an object, so that when an object changes state, all its dependents are notified and updated automatically! The principle of design in the observer pattern is to change the state of the subject and the number of observers. With this pattern, you can change objects that depend on the subject state, without changing the theme. --Find out what is going to change in the program, and then separate it from the fixed aspect! Both themes and observers use interfaces: The Observer uses the interface of the topic to register the subject, and the subject uses the Observer interface to notify the Observer. This allows the two to function normally, but also has the advantage of loose coupling! --Programming for the interface, not for the implementation of programming!. The Observer pattern uses "combination" to combine many observers into the subject. This relationship between objects (the Observer-subject) is not generated by inheritance, but by the way the composition is used at run time. --Multi-use combination, less use inheritance! Code
<?php
/**
* 观察者模式
* @author: Mac
* @date: 2012/02/22
*/
class
Paper{
/* 主题 */
private
$_observers
=
array
();
public
function register(
$sub
){
/* 注册观察者 */
$this
->_observers[] =
$sub
;
}
public
function trigger(){
/* 外部统一访问 */
if
(!
empty
(
$this
->_observers)){
foreach
(
$this
->_observers
as
$observer
){
$observer
->update();
}
}
}
}
/**
* 观察者要实现的接口
*/
interface
Observerable{
public
function
update();
}
class
Subscriber
implements
Observerable{
public
function update(){
echo
"Callback\n"
;
}
}
|
Here is the test code
/* 测试 */ $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 subject (also called an observer) (there are many ways to register it, or you can register it at the time of construction or the interface that the framework accesses), and then the implementation code is directly in the interface of the new object. This reduces the coupling of the subject object and the Observer object.
The observer pattern for PHP design Patterns