Policy mode:
A policy pattern is an object's behavior pattern, intended to encapsulate a set of algorithms. Dynamically select the desired algorithm and use it.
A strategy pattern refers to a pattern in a program that involves decision control. The policy pattern is very powerful because the core idea of the design pattern itself is the idea of the object-oriented programming of multiple forms.
Three roles for a policy pattern:
1. Abstract policy role
2. Specific policy roles
3. Environment role (reference to abstract policy role)
Implementation steps:
1. Define abstract role classes (common abstract methods that define each implementation)
2. Define a specific policy class (a common way to implement the parent class)
3. Define the Environment Role class (privatization statement abstract role variables, overloaded constructor methods, executing abstract methods)
Code instance for the policy pattern:
< PHP
Abstract class Baseagent {//Abstract policy class
Abstract function PrintPage ();
}
Class (Environment role) that is invoked when the client is IE
Class Ieagent extends Baseagent {
function PrintPage () {
Return ' IE ';
}
}
Class to invoke when the client is not IE (environment role)
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 ());
>
Outside the programming world, there are many examples of policy patterns. For example:
If I need to go from home to work in the morning, I can have a few strategies to consider: I can take the subway, ride the bus, walk or other way. Each policy can achieve the same result, but uses different resources.