This is the second day of my participation in the August More Text Challenge.

preface

As one of the three basic structures of programming (sequence, loop and judgment), judgment is often encountered in daily development. How to write sentences is the expression of xiaobai entry grammar, but also the big guy optimization goal, then how to write people at a glance, extensible, low coupling judgment sentence nan?

That is about to introduce today’s leading role strategy pattern, there may be some friend is confused about the concept of design patterns, but don’t be afraid, we only to learn about the ideas of design patterns, specific how to use the code to achieve, that is different from person to person, nan so you don’t have to follow the code of writing, only to understand the strategy pattern and part of the code

Thinking gradually into the

We can leave the theoretical definition of a strategic pattern behind and start with a small example:

E-commerce projects often encounter such a scenario, the order status code == “order status

The first option: if else is definitely the one we can think of immediately, and it’s also the easiest way to understand

// Order status 1: to be shipped 2: shipped 3: Let orderState = 1 if (orderState == 1) {console.log(" to be shipped ")} else if (orderState == 2) {console.log(" shipped ")} else If (orderState == 3) {console.log(" Received ")}Copy the code

The second scheme: through the mode of strategy

// Algorithm set == "let stateStrategy = {1: () => {console.log(" shipped ")}, 2: () => {console.log(" shipped ")}, 3: () => {console.log(" received ")}} // holds a reference to the policy body, Context function execFn(orderState){stateStrategy[orderState]()} let orderState = 1 execFn(orderState)Copy the code

One look, wow!! Obviously the use of policy mode will be more code, and several structures, not bring any optimization!! Don’t just look at the flaws in the strategic model. Learn to see the beauty within it.

  • If the demand changes now, we need to add “to be returned, returned, then the scheme can only add else if judgment, which will break the previous structure; However, in scheme 2, the main body of the policy can be directly modified without affecting the core logic of the code, making the code easier to understand and expand.

  • The abstracted policy body is highly reusable and can write multiple calls at once while encapsulating global methods.

    For example, when encapsulating form validation methods, there are only a few essential algorithms: non-null, regular matching, and length limiting. As long as we pull out these algorithms we don’t have to write them over and over again

  • Of course, the most important thing is that both the beauty of the code and the clarity of the code are much more elegant than multiple if and else.

Introduction to the policy pattern

In fact, the above code is almost perfect to illustrate the policy pattern, let’s take another example, you can imitate the above writing method, complete the policy body, policy allocation function.

/** * Users buy goods, according to the user's membership level, hit the corresponding discount, return the last price * 1 = "no member, no discount * 2 =" silver member, 10% off * 3 = "gold member, */ let stateStrategy = new Map([[1, (price) => {return price}], [2, (price) => {return price * 0.9}], [3, (price) => {return price * 0.8}]]) function context(userType, price) { return stateStrategy.get(userType)(price) } context(2, 60)Copy the code

Learning the strategy pattern is easy, but knowing which scenarios can be used is more difficult. It’s a matter of daily accumulation, reading other people’s code.

When you use if else, you can think about whether I’m going to expand this later, whether there are too many if else’s, and how complex the code is. If you are sure that you meet any of the above criteria, then you can consider a strategic model.

Characteristics of the policy pattern

  • The policy pattern is only suitable for managing a set of algorithms of the same type, and these algorithms are completely mutually exclusive (data parallelization), that is, only one of multiple algorithms can be effective at any one time. It is not suitable for code with high correlation of multiple judgment conditions.
  • The focus of the strategy pattern is not on how algorithms are implemented, but how they are organized and invoked to make the program structure more flexible, maintainable, and extensible.
  • Policy bodies can be reused or switched between them

Use scenarios such as: back-end return status code judgment, form verification.

advantages
  • It conforms to the principles of modified closure, operational addition and single function
disadvantages
  • The user must know the algorithm for all policy classes and decide which algorithm to use. This means that users must understand the differences between these algorithms in order to choose the right algorithm class at the right time.
  • To define multiple objects, resulting in memory footprint

After the speech

The essence of design patterns is to give you ideas when programming, not to limit your thinking and creation, only the rational use of design patterns, to write pleasing code