Php design pattern policy pattern
Rule mode:
The rule mode is the behavior mode of an object and is intended to encapsulate a group of algorithms. Dynamically select and use the desired algorithm.
Policy mode refers to a model that involves decision control in a program. The rule mode is very powerful, because the core idea of this design mode itself is the multiform idea of object-oriented programming.
Three roles in Rule mode:
1. abstract policy role
2. Specific policy roles
3. Environment role (reference to abstract policy role)
Steps:
1. Define the abstract role class (define the common abstract methods of each implementation)
2. define a specific policy class (a common method for implementing the parent class)
3. Define the environment (Private statement abstract role variables, heavy-load constructor methods, and execution of abstract methods)
Code example of policy mode:
<Php
Abstract class baseAgent {// abstract policy class
Abstract function PrintPage ();
}
// Used for the class (Environment role) called when the client is IE)
Class ieAgent extends baseAgent {
Function PrintPage (){
Return 'ie ';
}
}
// Used for the class (Environment role) called when the client is not IE)
Class otherAgent extends baseAgent {
Function PrintPage (){
Return 'not ie ';
}
}
Class Browser {// specific policy role
Public function call ($ object ){
Return $ object-> PrintPage ();
}
}
$ Bro = new Browser ();
Echo $ bro-> call (new ieAgent ());
>
In addition to the programming field, there are many examples of policy patterns. For example:
If I need to go to work from home in the morning, I have several strategies to consider: I can take the subway, take a bus, walk or another way. Each policy can get the same result, but different resources are used.