First of all, the definition, the first to look at the use of the scene, these definitions, Lao Meng, from the scene to think of design patterns is clearly a better way to understand.
Scenario: New user name after registering to complete the work: 1, new users to send points 2, new users send coupons 3, record the new user log log
Viewer mode:
Through the scene we can analyze, when the user registration, the system to execute a series of business logic, we can think of this series of business logic as observers, respectively, the product Classification observer, Coupon class observer, log Class observer,
These observers have been listening to the user class, and when the user performs the registration, the observers start their own business logic.
Analysis: The entire application scenario can have two classes complete, one is the Observer class, the other is the observed class (subject), they have their own interface, the Observer class interface is received by the Observer's notification, the update State, the Observer interface is
<?php
Subject class Interface (Observer)
Interface subjectinterface{
Public function addobserver ();
}
Viewer interface
Interface observerinterface{
Public function beginactionafternotifity ();
}
Subject class
Class Subject implements subjectinterface{
Private $_oberver=array ();
Add Observer
Public Function Addobserver ($oberver) {
$this->_oberver[]= $oberver;
}
Notice
Public Function notifity () {
foreach ($this->_oberver as $oberver) {
$oberver->beginactionafternotifity ();
}
}
}
Integral class
Class Point implements Observerinterface{
Public Function beginactionafternotifity () {
echo "Send points";
}
}
Coupon Class
Class Coupon implements observerinterface{
Public Function beginactionafternotifity () {
echo "Gift coupon";
}
}
Log class
Class Log implements observerinterface{
Public Function beginactionafternotifity () {
echo "You have been recorded";
}
}
Action class
Class User {
function AddUser () {
After adding a new user
$this->addobserver ();
}
function Addobserver () {
$subject =new subject ();
$subject->addobserver (new Point ());
$subject->addobserver (New Coupon ());
$subject->addobserver (New Log ());
}
}
PHP Watcher Mode