Home > Article > Backend Development > PHP design pattern strategy pattern_PHP tutorial
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.