Detailed Explanation of Policy Pattern Application Case of php Design Pattern

  • 2021-12-11 17:33:45
  • OfStack

This paper illustrates the application of policy pattern in php design pattern. Share it for your reference, as follows:

Strategic pattern

Definition:

The policy pattern defines a series of algorithms, encapsulates each algorithm, and allows them to be interchangeable. The policy pattern allows the algorithm to change independently of the customers who use it.

Role analysis:

Abstract policy role: policy class, usually implemented by an interface or abstract class; Specific strategic roles: packaging related algorithms and behaviors; Environment role: Hold a reference to a policy class, which is finally used by the client.

Application scenario:

Multiple classes are only different in performance behavior, so you can use policy mode to dynamically select specific behaviors to be executed when running. Different strategies (algorithms) need to be used in different situations, or strategies may be implemented in other ways in the future. Hide the implementation details with policies (algorithms) from customers, which are completely independent of each other.

Code implementation:


<?php
/**
 * Created by PhpStorm.
 * Author: zhaorui
 * Date: 2019/2/27
 * Time: 10:55
 */
header('Content-Type:text/html;charset=utf-8');
//  Abstract policy interface 
abstract class Strategy{
  abstract function wayToSchool();
}
// Specific strategic roles 
class BikeStrategy extends Strategy{
  function wayToSchool()
  {
    echo " Go to school by bike ".PHP_EOL;
  }
}
class BusStrategy extends Strategy{
  function wayToSchool()
  {
    echo " Go to school by bus ".PHP_EOL;
  }
}
class TaxiStrategy extends Strategy{
  function wayToSchool()
  {
    echo " Go to school by taxi ".PHP_EOL;
  }
}
//  Environmental role 
class Context{
  private $strategy;
  function getStrategy($strategyName){
    try{
      $strategyReflection = new ReflectionClass($strategyName);
      $this->strategy = $strategyReflection->newInstance();
    }catch (ReflectionException $e){
      $this->strategy = "";
    }
  }
  function goToSchool(){
    $this->strategy->wayToSchool();
  }
}
//  Test 
$context  = new Context();
$context->getStrategy('BusStrategy');
$context->goToSchool();

Running result

Go to school by bus

Advantages:

Policy pattern provides a way to manage related algorithm families. The hierarchical structure of a policy class defines a family of algorithms or behaviors. Proper use of inheritance can transfer common code to the parent class, thus avoiding duplicate code. Policy patterns provide a way to replace inheritance relationships. Inheritance can handle a variety of algorithms or behaviors. If the policy pattern is not used, the environment class that uses an algorithm or behavior may have 1 subclass, each of which provides a different algorithm or behavior. However, the user of such an algorithm or behavior is mixed with the algorithm or behavior itself. The logic of deciding which algorithm to use or which behavior to take is mixed with the logic of algorithm or behavior, so it is impossible to evolve independently. Inheritance makes it impossible to change algorithms or behaviors dynamically. Using policy mode can avoid using multiple conditional transition statements. Multiple transfer statement is not easy to maintain. It mixes the logic of which algorithm or behavior to adopt with the logic of algorithm or behavior in one case, and all of them are listed in one multiple transfer statement, which is more primitive and backward than the method of inheritance.

Disadvantages:

The client must know all the policy classes and decide which one to use. This means that the client must understand the differences between these algorithms in order to choose the appropriate algorithm class at the right time. In other words, the policy pattern is only applicable to all the algorithms or behaviors that the client knows. Policy patterns result in many policy classes, and each specific policy class will produce a new class. Sometimes policy classes can be designed to be shared by saving environment-dependent state to clients, so that policy class instances can be used by different clients. In other words, you can use the meta-pattern to reduce the number of objects.

More readers interested in PHP can check out the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: