Principle and Usage Analysis of Policy Pattern in PHP Design Pattern

  • 2021-12-05 05:39:16
  • OfStack

This paper illustrates the principle and usage of policy pattern of PHP design pattern. Share it for your reference, as follows:

Policy Mode (Strategy Pattern)

Policy pattern is the behavior pattern of objects, which is intended to encapsulate a group of algorithms. Dynamically select the required algorithm and use it.

Policy mode refers to a mode involved in decision control in the program. Policy pattern is very powerful because the core idea of this design pattern itself is the polymorphic idea of object-oriented programming.

Three roles of policy mode:

1. Abstract policy roles

2. Specific strategic roles

3. Environment roles (references to abstract policy roles)

Implementation steps:

1. Define abstract role classes (define common abstract methods for each implementation)

2. Define a specific policy class (implement the common method of the parent class concretely)

3. Define environment role classes (privatize declaring abstract role variables, overloading constructors, executing abstract methods)

Code example of policy mode:


<?php
  abstract class baseAgent { // Abstract policy class 
    abstract function PrintPage();
  }
  // For the client is IE Class called when (environment role) 
  class ieAgent extends baseAgent {
    function PrintPage() {
      return 'IE';
    }
  }
  // Used for clients that are not IE Class called when (environment role) 
  class otherAgent extends baseAgent {
    function PrintPage() {
      return 'not IE';
    }
  }
  class Browser { // Specific strategic roles 
    public function call($object) {
      return $object->PrintPage ();
    }
  }
  $bro = new Browser ();
  echo $bro->call ( new ieAgent () );
?>

Run results:

IE

Just outside the programming field, there are many examples about policy patterns. For example:

If I need to go to work from home in the morning, I can have several strategies to consider: I can take the subway, take the bus, walk or other ways. Each strategy can get the same result, but different resources are used.

For more readers interested in PHP related content, please check 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 Skills" and "Summary of php Common Database Operation Skills"

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


Related articles: