Strategy of PHP design pattern

Time:2020-11-24

This paper describes the strategy pattern strategy of PHP design pattern. For your reference, the details are as follows:

1. Overview

In software development, there are many algorithms to realize a certain functionStrategy, we can choose different algorithms or strategies according to different environment or conditions to complete the function。 For example, hard coding is a commonly used method in a class. If you need to provide a variety of search algorithms, you can write these algorithms to a class, provide multiple methods in this class, and each method corresponds to a specific search algorithm. Of course, you can encapsulate these search algorithms in a unified method, and use if else… Or case. We can call these two methods hard coding. If we need to add a new search algorithm, we need to modify the source code that encapsulates the algorithm class; to replace the search algorithm, we also need to modify the client calling code. A large number of search algorithms are encapsulated in this algorithm class,This kind of code will be more complex and difficult to maintain. If we include these strategies on the client side, this method is more undesirable, which will lead to the client program being huge and difficult to maintain. If there are a large number of algorithms to choose from, the problem will become more serious

“1” or “1” can be used to determine whether the user’s preferred menu can be arranged horizontally or not. Colleagues can flexibly add the display style of the menu.

Example 2: Travel: we can have several strategies to consider: we can ride bicycles, cars, trains, airplanes. Each policy can get the same result, but they use different resources. The choice of strategy is based on cost, time, tools, and the convenience of each method.

2. Problems

How to separate the algorithm from the object so that the algorithm can be changed independently of the client who uses it?

3. Solutions

Strategy modelDefine a series of algorithms, encapsulate each algorithm and make them replaceable. This pattern allows the algorithm to vary independently of the client who uses it. also known asPolicy。(Definea family of algorithms,encapsulate each one, andmake them interchangeable. Strategy lets the algorithmvary independently from clients that use it. )

The strategy pattern distinguishes the object itself from the operation rules, and its function is very powerful, because the core idea of the design pattern itself is the polymorphy of object-oriented programming.

4. Applicability

Use the strategy pattern when

1) Many related classes simply behave differently. Policy provides a way to configure a class with one of several behaviors. That is, a system needs to choose one of several algorithms dynamically.

2) · different variants of an algorithm need to be used. For example, you may define algorithms that reflect different space / time tradeoffs. When these variants are implemented as the class level of an algorithm, the policy pattern can be used.

3) The algorithm uses data that customers should not know. Policy patterns can be used to avoid exposing complex, algorithm related data structures.

4) A class defines multiple behaviors, and these behaviors appear in the form of multiple conditional statements in the operation of this class. Move the relevant conditional branches into their respective strategy classes to replace these conditional statements.

5. Structure

6. Composition of the model

Context:Use a ConcreteStrategy object to configure. Maintain a reference to the strategy object. You can define an interface for strategy to access its data.
Abstract strategy class:Defines a common interface for all supported algorithms. Context uses this interface to call a concrete strategy defined algorithm.
Concrete strategy class:The strategy interface is used to implement a specific algorithm.

7. Effect

The strategy model has the following advantages:

1) Correlation algorithm seriesThe strategy class level defines a series of reusable algorithms or behaviors for context. Inheritance helps to extract the common functions of these algorithms.
2) Provides a way to replace inheritance relationshipsInheritance provides another way to support multiple algorithms or behaviors. You can directly generate a subclass of the context class to give it different behaviors. However, this will make the behavior hard line into context, and mix the implementation of the algorithm with the implementation of context, which makes the context difficult to understand, difficult to maintain and difficult to expand, and can not dynamically change the algorithm. You end up with a bunch of related classes, and the only difference between them is the algorithm or behavior they use. Encapsulating the algorithm in a separate strategy class enables you to change it independently of its context, making it easy to switch, understand and expand.
3) Some if else conditional statements are eliminatedThe strategy pattern provides an alternative to using conditional statements to select the desired behavior. When different behaviors are stacked in a class, it is difficult to avoid using conditional statements to select the appropriate behavior. Encapsulating the behavior in a separate strategy class eliminates these conditional statements. Code with many conditional statements usually means that the strategy pattern needs to be used.
4) The choice of implementationThe strategy pattern can provide different implementations of the same behavior. Customers can choose from different strategies according to different time / space trade-off requirements.

Disadvantages of strategy mode:

1) The client must know all the policy classes and decide which one to useA potential drawback of this model is that if a customer wants to choose an appropriate strategy, he must know how the strategies are different. At this point, you may have to expose specific implementation issues to the customer. Therefore, the strategy pattern is needed only when these different behavior variants relate to customer related behavior.
2) communication cost between strategy and contextRegardless of whether the algorithms implemented by ConcreteStrategy are simple or complex, they all share the interface defined by strategy. Therefore, it is likely that some concretestrategies will not use all the information passed to them through this interface; simple concretestrategies may not use any of them! This means that sometimes context creates and initializes parameters that will never be used. If there is such a problem, a closer coupling between strategy and context will be needed.
3) the strategy pattern will result in many policy classes: you can reduce the number of objects to a certain extent by using the share pattern. The number of objects in strategy increases. Sometimes you can reduce this overhead by implementing strategy as a stateless object that can be shared by contexts. Any remaining state is maintained by context. Context passes this state in every request to the strategy object. Shared strategies should not maintain state between calls.

8. Implementation

1) Travel:

uml:

Code implementation:

<?php
/**
*Strategy model
*Define a series of algorithms, encapsulate each algorithm, and make them replaceable. This pattern allows the algorithm to vary independently of the client who uses it
*
*/ 
 
/**
*Travel
*
* 
*/
interface TravelStrategy{
 public function travelAlgorithm();
} 
 
/**
 *Concrete strategy 1: Flying
 */
class AirPlanelStrategy implements TravelStrategy {
 public function travelAlgorithm(){
 echo "travel by AirPlain", "<BR>\r\n"; 
 }
} 
 
/**
 *Concrete strategy 2: take the train
 */
class TrainStrategy implements TravelStrategy {
 public function travelAlgorithm(){
 echo "travel by Train", "<BR>\r\n"; 
 }
} 
 
/**
 *Concrete strategy 3: cycling
 */
class BicycleStrategy implements TravelStrategy {
 public function travelAlgorithm(){
 echo "travel by Bicycle", "<BR>\r\n"; 
 }
} 
/**
 * 
 *Context: use a ConcreteStrategy object to configure. Maintain a reference to the strategy object. You can define an interface for strategy to access its data.
 *Algorithmic solution class to provide customers with the choice of solution to use:
 */
class PersonContext{
 private $_strategy = null;
 
 public function __construct(TravelStrategy $travel){
 $this->_strategy = $travel;
 }
 /**
 *Travel
 */
 public function setTravelStrategy(TravelStrategy $travel){
 $this->_strategy = $travel;
 }
 /**
 *Travel
 */
 public function travel(){
 return $this->_strategy ->travelAlgorithm();
 }
} 
 
//Travel by train
$person = new PersonContext(new TrainStrategy());
$person->travel();
 
//Change to cycling
$person->setTravelStrategy(new BicycleStrategy());
$person->travel();
 
?>

2) Sorting strategy: a system provides a class for manipulating array data, which encapsulates common operations on arrays,

Such as looking for array elements, sorting array elements and so on. Taking sorting operation as an example, this paper designs the array operation class using policy pattern,

The client can change the sorting algorithm dynamically, and can select bubble sort, select sort or insert sort according to the needs,

It can also flexibly add new sorting algorithm.

9. Other related models

1) State mode

Policy patterns are very similar to many other design patterns. The biggest difference between the policy mode and the state mode is that the policy mode only performs the conditional selection only once, while the state mode changes the execution mode continuously with the change of instance parameters (the state of the object instance). In other words, it’s just the pattern

The execution mode is changed when the object is initialized, while the state mode dynamically changes the execution mode of the object instance according to the cycle time of the object instance.

– yesThe number of states passing through the environment classTo decide whether to use policy mode or state mode.
The environment class of the policy mode chooses a specific policy class, and the specific policy class does not need to care about the environment class; andThe environment class of state mode needs to be put into a specific state due to external factors, so as to realize the state switching through its method, soThere is a bidirectional association between environment class and state class
When using the strategy mode,The client needs to know which specific policy to chooseWhen using state mode,The client does not need to care about the specific stateThe state of the environment class will be automatically converted according to the user’s operation.
If the objects of a certain class in the system have multiple states, the behavior is different in different states, and theseUse state mode when transitions can occur between states
If there are multiple implementations for a certain behavior of a class in the system, andPolicy patterns are used when these implementations are interchangeable

2) The difference between simple factories:

Factory pattern is a creation pattern, which focuses on the creation of objects and provides an interface for creating objects.
Policy pattern is an object behavior pattern, which focuses on the encapsulation of behavior and algorithm. It defines a series of algorithms, encapsulates each algorithm and makes them replaceable. The algorithm can be changed independently of the customers who use it

Take the example of travel mentioned above:
We go on a trip. Strategy mode: there are several options for you to travel, whether it’s better to travel by train or by bike. It’s entirely up to the customer to build a travel plan (for example, you need to buy train tickets or air tickets yourself). The factory mode is that after you decide which travel plan you decide, you don’t have to pay attention to how the travel plan is created for you. In other words, you can tell me the name of the scheme, and then the factory will build the specific scheme instead of you (the factory will buy the train ticket instead of you).

In the above example, the client code:


$person = new PersonContext(new TrainStrategy());
$person->travel();

We see that customers need to create specific travel (New trainstrategy ()) instances themselves. The concrete instance is passed on.

In the factory mode, you just need to tell which kind of travel you want. Instead of passing a specific instance, you can use a logo (travel scheme ID).

10. Summary and analysis

1) Strategy pattern is a design pattern that is easy to understand and use,Policy pattern is the encapsulation of algorithm. It separates the responsibility of algorithm from algorithm itself and delegate it to different object management。 Policy pattern usually encapsulates a series of algorithms into a series of policy classes as a subclass of an abstract policy class. In a word, “prepare a set of algorithms and encapsulate each algorithm so that they can be interchanged.”.

2) In the policy mode, it is up to the client to decide what specific policy role to use under what circumstances. 2)

3) The policy pattern only encapsulates the algorithm, providing the convenience of inserting new algorithm into the existing system and retiring the old algorithm from the system. The policy mode does not decide what algorithm to use when, and the choice of algorithm is decided by the client. This improves the flexibility of the system to a certain extent, but the client needs to understand the differences between all the specific policy classes in order to choose the appropriate algorithm. This is also one of the disadvantages of the policy mode, which increases the difficulty of using the client to a certain extent.

More about PHP related content interested readers can see this site topic: “PHP object-oriented programming introductory tutorial”, “PHP array (array) operation skills”, “PHP basic syntax introductory course”, “PHP operation and operator Usage Summary”, “PHP character string (string) Usage Summary”, “PHP + MySQL database operation introduction tutorial” and “PHP common database operation” Summary of writing skills

I hope this article will help you with PHP programming.

Recommended Today

Talking about Java collection

preface Most programming languages provide array to save objects, and array is one of the most important data structures. However, the length of the array has been defined during initialization, which is immutable and troublesome to use. Therefore, Java inJDK 1.2The collection framework is added to the version to save and manipulate objects. The container […]