The strategy model of PHP design pattern

Source: Internet
Author: User
Tags abstract define object define abstract return client
Policy mode:

A policy pattern is an object's behavior pattern, intended to encapsulate a set of algorithms. Dynamically select the desired algorithm and use it.

   

A strategy pattern refers to a pattern in a program that involves decision control. The policy pattern is very powerful because the core idea of the design pattern itself is the idea of the object-oriented programming of multiple forms.

   

   

   

Three roles for a policy pattern:

1. Abstract policy role

2. Specific policy roles

3. Environment role (reference to abstract policy role)

Implementation steps:

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

2. Define a specific policy class (a common way to implement the parent class)

3. Define the Environment Role class (privatization statement abstract role variables, overloaded constructor methods, executing abstract methods)

Code instance for the policy pattern:

< PHP

Abstract class Baseagent {//Abstract policy class

Abstract function PrintPage ();

}

Class (Environment role) that is invoked when the client is IE

Class Ieagent extends Baseagent {

function PrintPage () {

Return ' IE ';

}

}

Class to invoke when the client is not IE (environment role)

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

>

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

If I need to go from home to work in the morning, I can have a few strategies to consider: I can take the subway, ride the bus, walk or other way. Each policy can achieve the same result, but uses different resources.




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.