Home  >  Article  >  Backend Development  >  PHP design pattern strategy pattern_PHP tutorial

PHP design pattern strategy pattern_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:54:19882browse

Strategy Pattern of PHP Design Patterns

Strategy Mode:

Strategy pattern is the behavior pattern of an object, intended to encapsulate a set of algorithms. Dynamically select the required algorithm and use it.

 

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

 

 

 

Three characters in strategy mode:

1. Abstract Strategy Role

2. Specific strategic roles

3. Environment role (reference to abstract strategy role)

Implementation steps:

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

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

3. Define environment role classes (privately declare abstract role variables, overload construction methods, and execute abstract methods)

Code example of strategy pattern:

abstract class baseAgent { //Abstract strategy class

abstract function PrintPage();

}

//The class used when the client is IE (environment role)

class ieAgent extends baseAgent {

function PrintPage() {

return 'IE';

}

}

//The class used when the client is not IE (environment role)

class otherAgent extends baseAgent {

function PrintPage() {

return 'not IE';

}

}

class Browser { //Specific strategic role

public function call($object) {

return $object->PrintPage ();

}

}

$bro = new Browser ();

echo $bro->call ( new ieAgent () );

>

Just outside the realm of programming, there are many examples of the Strategy Pattern. 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 achieves the same results but uses different resources.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/998008.htmlTechArticleStrategy pattern of PHP design pattern Strategy pattern: Strategy pattern is the behavior pattern of an object, which is intended for a set of algorithms. Encapsulation. Dynamically select the required algorithm and use it. Strategy pattern refers to...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn