Observer Mode: The Observer design mode makes it easier to create and view objects in the target object state, 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 the code coupling... SyntaxHighlighter. all (); Observer pattern
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]
// 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
// 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
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service