A policy pattern is a behavior pattern of an object intended to encapsulate a set of algorithms. Dynamically select the required algorithm and use it.
Policy mode refers to a mode in a program that involves decision control. The strategy pattern is powerful because the core idea of the design pattern itself is the idea of object-oriented programming pluralism.
Three roles in policy mode:
1. Abstract Policy role
2. Specific policy roles
3. Context roles (references to abstract policy roles)
Implementation steps:
1. Define abstract role classes (define common abstract methods for each implementation)
2. Define concrete policy classes (common methods for concrete implementation superclasses)
3. Define environment role classes (private declare abstract role variables, overload constructors, execute abstract methods)
Let’s take e-commerce price calculation as a simple example to illustrate: there are different algorithms to calculate the price, such as full reduction, discount and so on
We start by declaring the behavior interface of the policy
<? PHP /* * the interface to declare the policy, specifying the behavior contained in the policy. */ interface Strategy { function getTitle(); function getPrice(); }Copy the code
Then we declare the specific product class
/** * implements Strategy {public function getTitle() {echo 'implements Strategy '; } public function getPrice($money) { return $money-10; } /** * implements Strategy {public function getTitle() {echo 'implements Strategy '; } public function getPrice($money) {return $money*0.5; }}Copy the code
Define a policy factory class to construct different product classes
class StrategyFactory { private $strategy_mode; Public function __construct($mode) {$this->strategy_mode = $mode; Public function getTitle() {$this->strategy_mode->getTitle(); Public function getPrice($money) {$this->strategy_mode->getPrice($money); }}Copy the code
Client testing
<? $mode1 = new StrategyFactory(new ManJianStrategy()); $mode1->getTitle(); $mode1->getPrice(100); $mode2= new StrategyFactory(new DaZheStrategy()); $mode2->getTitle(); $mode2->getPrice(100);Copy the code
If you want to extend the calculation in the future, such as the original price, then write a original price class on the line