Php design pattern policy pattern

Source: Internet
Author: User

Php design pattern policy pattern
Rule mode:

The rule mode is the behavior mode of an object and is intended to encapsulate a group of algorithms. Dynamically select and use the desired algorithm.

   

Policy mode refers to a model that involves decision control in a program. The rule mode is very powerful, because the core idea of this design mode itself is the multiform idea of object-oriented programming.

   

   

   

Three roles in Rule mode:

1. abstract policy role

2. Specific policy roles

3. Environment role (reference to abstract policy role)

Steps:

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

2. define a specific policy class (a common method for implementing the parent class)

3. Define the environment (Private statement abstract role variables, heavy-load constructor methods, and execution of abstract methods)

Code example of policy mode:

 

<Php

 

Abstract class baseAgent {// abstract policy class

Abstract function PrintPage ();

}

// Used for the class (Environment role) called when the client is IE)

Class ieAgent extends baseAgent {

Function PrintPage (){

Return 'ie ';

}

}

// Used for the class (Environment role) called when the client is not IE)

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 ());

>

 

 

In addition to the programming field, there are many examples of policy patterns. For example:

 

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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.