Introduced
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 automatically updated!
Design principles
In the Observer pattern, the status of the subject and the number of observers are changed. With this pattern, you can change objects that depend on the subject's state without having to change the subject. --Identify the changing aspects of the program and separate it from the fixed aspect!
Themes and observers use interfaces: The Observer uses the interface of the subject to register with the subject, and the subject notifies the observer by using the Observer interface. This allows the two to operate normally, but also has the advantage of loose coupling! --for interface programming, not for implementation programming!
。
The Observer pattern combines many observers into the subject using a "combination". This relationship between objects (Observer-subject) is not generated through inheritance, but is generated at runtime using a combination of methods. Multi-use combination, less inheritance!
Code
Copy Code code as follows:
<?php
/**
* Observer mode
* @author: Mac
* @date: 2012/02/22
*/
Class paper{/* Theme * *
Private $_observers = Array ();
Public Function Register ($sub) {/* Registration Observer/*
$this->_observers[] = $sub;
}
Public Function trigger () {/* External uniform 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";
}
}
Here is the test code
?
* * Test/*
$paper = new paper ();
$paper->register (new Subscriber ());
$paper->register (New Subscriber1 ());
$paper->register (New Subscriber2 ());
$paper->trigger ();
Summarize
When a new object is to be filled in, it is only necessary to register in the subject (also called an observer) (there are many ways of registering, you can also register at the time of construction, or in the interface that the framework accesses), and then implement the code directly in the interface of the new object. This reduces the degree of coupling between the subject object and the Observer object.
A good design pattern does not go directly into your code, but into your brain.