Analysis of the principle and usage of the strategy pattern of PHP design pattern


In this paper, an example is given to illustrate the principle and usage of the strategy pattern of PHP design pattern. To share with you for your reference, as follows:

Strategy pattern

Policy pattern is the behavior pattern of an object, which is intended to encapsulate a group of algorithms. Dynamic selection of the required algorithm and use.

Strategy mode refers to a mode involving decision control in the program. The strategy pattern is very powerful, because the core idea of the design pattern itself is the multiformity idea of object-oriented programming.

There are three roles in the policy pattern:

1. Abstract policy role

2. Specific strategic roles

3. Environment role (reference to abstract policy role)

Implementation steps:

1. Define the abstract role class (define the common abstract methods of each implementation)

2. Define specific policy classes (common methods to implement parent classes)

3. Define the environment role class (privatization states Abstract role variables, overloading construction methods, executing abstract methods)

Code instance of policy mode:

  Abstract class baseagent {// abstract policy class
    abstract function PrintPage();
  //Used for classes (environment roles) called when the client is IE
  class ieAgent extends baseAgent {
    function PrintPage() {
      return 'IE';
  //For classes (environment roles) called when the client is not IE
  class otherAgent extends baseAgent {
    function PrintPage() {
      return 'not IE';
  Class browser {// specific policy roles
    public function call($object) {
      return $object->PrintPage ();
  $bro = new Browser ();
  echo $bro->call ( new ieAgent () );

Operation result:


Just outside the programming world, there are many examples of policy patterns. For example:

If I need to go to work from home in the morning, I can think about several strategies: I can take the subway, take the bus, walk or other ways. Each policy can get the same result, but uses different resources.

For more information about PHP, please refer to the following topics: PHP object-oriented programming introduction, PHP array operation skills, PHP basic syntax introduction, PHP operation and operator usage summary, PHP string usage summary, PHP + MySQL database operation introduction and PHP common database operation Skills summary

I hope this article is helpful for PHP programming.

Recommended Today

Big data Hadoop — spark SQL + spark streaming

catalogue 1、 Spark SQL overview 2、 Sparksql version 1) Evolution of sparksql 2) Comparison between shark and sparksql 3)SparkSession 3、 RDD, dataframes and dataset 1) Relationship between the three 1)RDD 1. Core concept 2. RDD simple operation 3、RDD API 1)Transformation 2)Action 4. Actual operation 2)DataFrames 1. DSL style syntax operation 1) Dataframe creation 2. SQL […]