How do I learn the algorithm strategy

Preface

In daily development we often have to use different processing logics for different business units in the same context. To take a simple example, when we make purchases and billing on ecommerce websites, different levels of preference often apply to different levels of our members. From a system implementation point of view, we need to decide whether to use them depending on the different requirements during operation of a particular algorithm strategy. Strategy mode can better solve this problem. This blog explains the strategy mode.

Strategy mode

The strategy pattern defines a set of algorithms, encapsulates each algorithm and allows them to be substituted for one another so that the algorithm can change regardless of the customers who use it.

The class diagram of the strategy pattern is as follows:

As can be seen from the figure above, the strategy model consists of three components:

  • context Keep a strategy reference;

  • Abstract strategy (strategy) Abstract roles, usually implemented by an interface or abstract class;

  • Concrete strategy (ConcreteStrategy) Packaged related algorithms or behaviors.

Typical implementation

Let's take the e-commerce preference guidelines mentioned in the opening chapter as an example and consider the typical implementation code of the strategy model. First we have to define a strategy interface to calculate the discount amount

And three implementation classes that represent three different billing strategies

We also need to define a consumer business unit that will play the environmental role mentioned above

Finally, let's test the code functionality

The results are as follows