Observer Mode
The observer design pattern makes it easier to create and view objects in the state of the target object, and provides top-down functionality that is not coupled with the core object. The observer design pattern is very commonly used. In a complex WEB system, the observer pattern can help you relieve the code design pressure and reduce code coupling.
Scenario Design
Design an order class
After the order is created, various actions are performed, such as sending an EMAIL or changing the order status.
The original method is to write these operations in the create FUNCTION.
However, as order creation classes become larger and larger, such operations cannot meet the needs and change rapidly.
In this case, the observer mode appears.
Code Design:
[Php]
<? Php
// The observer design mode makes it easier to create and view objects in the target object state, and provides the top-level functionality that is not coupled with the core object.
// The observer design pattern is very commonly used. In a complex WEB system, the observer pattern can help you relieve the code design pressure and reduce code coupling.
// Take a shopping process as an Example
Class order {
Protected $ observers = array (); // store the observation container
// Add observer
Public function addObServer ($ type, $ observer ){
$ This-> observers [$ type] [] = $ observer;
}
// Run the observer
Public function obServer ($ type ){
If (isset ($ this-> observers [$ type]) {
Foreach ($ this-> observers [$ type] as $ obser ){
$ A = new $ obser;
$ A-> update ($ this); // public Method
}
}
}
// Order purchase process
Public function create (){
Echo 'purchase successful ';
$ This-> obServer ('buy'); // buy action
}
}
Class orderEmail {
Public static function update ($ order ){
Echo 'send an email successfully purchased ';
}
}
Class orderStatus {
Public static function update ($ order ){
Echo 'change order status ';
}
}
$ Ob = new order;
$ Ob-> addObServer ('buy', 'orderemail ');
$ Ob-> addObServer ('buy', 'orderstatus ');
$ Ob-> create ();
Author: initphp