Home > Web Front-end > JS Tutorial > body text

How to use the strategy pattern of design patterns in the front-end

php中世界最好的语言
Release: 2018-05-24 09:50:30
Original
1361 people have browsed it

This time I will bring you Design patternStrategy patternHow to use it in the front-end, how to use the strategy pattern of the design pattern in the front-endNotesYes Which ones, the following are practical cases, let’s take a look.

What is the strategy pattern?

In the classic "Design Pattern" by the four GoF brothers, the strategy pattern is defined as follows:

Define a series of algorithms, encapsulate them one by one, and make them interchangeable.

The above sentence is very simple literally. But how to apply it in the development process is still confusing with just one definition. Take the merchant purchase, sale and inventory system that the author once worked on as an example:

A supermarket is preparing to hold a promotional event, and the market staff has formulated some promotional strategies after investigation and analysis:
  1. 10 off for purchases over 100

  2. 30 off for purchases over 200

  3. 50 off for purchases over 300

  4. . . .

The interface of the cashier software is like this (simple illustration):

How to use the strategy pattern of design patterns in the front-end

How should we calculate the actual consumption amount?

The initial implementation is like this:

//方便起见,我们把各个促销策略定义为枚举值:0,1,2...
var getActualTotal = function(onSaleType,originTotal){
    if(onSaleType===0){
        return originTotal-Math.floor(originTotal/100)*10
    }
    if(onSaleType===1){
        return originTotal-Math.floor(originTotal/200)*30
    }
    if(onSaleType===0){
        return originTotal-Math.floor(originTotal/300)*50
    }
}
getActualTotal(1,2680); //2208
Copy after login
Copy after login

The above code is very simple, and the shortcomings are also obvious. As my full reduction strategy gradually increases, the getActualTotal function will become larger and larger, and it is full of if judgments. It is easy to make mistakes if you are not careful.

OK, some people say that I am lazy. Although this is not elegant enough, it does not affect my use. After all, no matter how many full reduction strategies are used, it will not be enough.
I can only say that requirements are never determined by programmers. . At this time, the market staff said that our new version of the program has added membership functions, and we need to support the following promotion strategies:

Member promotion strategy:
  1. Members recharge 300 and get 60, And the first single purchase is 10% off

  2. Members recharge 500 and get 100 yuan back, and the first single purchase is 20% off

  3. Members recharge 1,000 and the first single purchase is 7 Fold

  4. ...

At this time, if you are still adding ## to the original getActualTotal function #if Judgment, I think if your leader reviews your code, he may wonder why he hired you in the first place. .

OK, we finally decided to refactor the code of the promotion strategy. We can do this:

var vipPolicy_0=function(originTotal){
    return originTotal-Math.floor(originTotal/100)*10
}
var vipPolicy_1=function(originTotal){
    return originTotal-Math.floor(originTotal/200)*30
}
...
//会员充1000返300
var vipPolicy_10=function(account,originTotal){
    if(account===0){
        account+=1300;
        return originTotal*0.9
    }else{
        account+=1300;
        return originTotal;
    }
    return originTotal-Math.floor(originTotal/200)*30
}
...
var vipPolicy_n=function(){
    ...
}
var getActualTotal=function(onSaleType,originTotal,account){
    switch(onSaleType){
        case 0:
            return vipPolicy_0(originTotal);
        case 1:
            return vipPolicy_0(originTotal);
        ...
        case n:
            return ...
        default:
            return originTotal;
    }
}
Copy after login
Copy after login
Okay, now each of our strategies has its own independent space. It seems Be well organized. But there are still two problems that have not been solved:

  1. With the increase of promotional strategies, the code volume of

    getActualTotal will still become larger and larger

  2. The system lacks flexibility. If you need to add a strategy, in addition to adding a strategy function, you also need to modify the

    switch...case.. statement

Let us review the definition of the strategy pattern again:

Define a series of algorithms, encapsulate them one by one, and make them interchangeable
In our example, The implementation of each promotional strategy is different, but our ultimate goal is to obtain the actual amount. The strategy pattern can encapsulate our algorithms for promotional strategies one by one and make them interchangeable without affecting our evaluation of the actual amount. This is exactly what we need.

Let’s use the strategy pattern to reconstruct the above code:

var policies={
    "Type_0":function(originTotal){
        return originTotal-Math.floor(originTotal/100)*10 
    },
    "Type_1":function(originTotal){
        return originTotal-Math.floor(originTotal/200)*30 
    },
    ...
    "Type_n":function(originTotal){
        ... 
    }
}
var getActualTotal=function(onSaleType,originTotal,account){
    return policies["Type_"+onSaleType](originTotal,account)
}
//执行
getActualTotal(0,2680.00);//2208
Copy after login
Copy after login
Analyzing the above code, we found that no matter how the promotion strategy is increased, the

getActualTotal function does not need to be updated at all. Changed. All we have to do is add the function of the new strategy.

Through the strategy pattern code, we eliminate the stomach-churning conditional branch statements.

getActualTotal itself has no computing power, but delegates the calculation to the strategy function.

From this we can summarize the key points of the strategy pattern implementation:

  1. Encapsulate the changing algorithm into an independent strategy function and be responsible for the specific calculation

  2. Delegation function, this function accepts customer requests and delegates the request to a specific strategy function

It is represented by a UML diagram as follows:
How to use the strategy pattern of design patterns in the front-end

How about it? Now that you see the picture above, do you have a clear understanding? Then hurry up and try the strategy mode!


Reference books:

  1. "Design Patterns: ReusableObject-orientedBasics of Software"

  2. 《Dahua Design Pattern》

  3. ##《JavascriptDesign Pattern and Development Practice 》

I have been doing front-end development for several years, but I have never studied and summarized the design patterns in depth. As I do more and more architecture-related work, I feel more and more that design patterns have become an obstacle on my way forward. So start today to deeply study and summarize classic design patterns and several major object-oriented principles.
On the first day of today, let’s talk about strategy mode first.

What is the strategy pattern?

In the classic "Design Pattern" by the four GoF brothers, the strategy pattern is defined as follows:

Define a series of algorithms, encapsulate them one by one, and make them interchangeable.
The above sentence is very simple literally. But how to apply it in the development process is still confusing with just one definition. Take the merchant purchase, sale and inventory system that the author once worked on as an example:

A supermarket is preparing to hold a promotional event, and the market staff has formulated some promotional strategies after investigation and analysis:
  1. 10 off for purchases over 100

  2. 30 off for purchases over 200

  3. 50 off for purchases over 300

  4. . . .

The interface of the cashier software is like this (simple illustration):

How to use the strategy pattern of design patterns in the front-end

How should we calculate the actual consumption amount?

The initial implementation is like this:

//方便起见,我们把各个促销策略定义为枚举值:0,1,2...
var getActualTotal = function(onSaleType,originTotal){
    if(onSaleType===0){
        return originTotal-Math.floor(originTotal/100)*10
    }
    if(onSaleType===1){
        return originTotal-Math.floor(originTotal/200)*30
    }
    if(onSaleType===0){
        return originTotal-Math.floor(originTotal/300)*50
    }
}
getActualTotal(1,2680); //2208
Copy after login
Copy after login
The above code is very simple, and the shortcomings are also obvious. As my full reduction strategy gradually increases, the

getActualTotal function will become larger and larger, and it is full of if judgments. It is easy to make mistakes if you are not careful.

OK, some people say that I am lazy. Although this is not elegant enough, it does not affect my use. After all, no matter how many full reduction strategies are used, it will not be enough.

I can only say that requirements are never determined by programmers. . At this time, the market staff said that our new version of the program has added membership functions, and we need to support the following promotion strategies:

Member promotion strategy:
  1. Members recharge 300 and get 60, And the first single purchase is 10% off

  2. Members recharge 500 and get 100 yuan back, and the first single purchase is 20% off

  3. Members recharge 1,000 and the first single purchase is 7 Fold

  4. ...

At this time, if you are still adding ## to the original

getActualTotal function #if Judgment, I think if your leader reviews your code, he may wonder why he hired you in the first place. . OK, we finally decided to refactor the code of the promotion strategy. We can do this:

var vipPolicy_0=function(originTotal){
    return originTotal-Math.floor(originTotal/100)*10
}
var vipPolicy_1=function(originTotal){
    return originTotal-Math.floor(originTotal/200)*30
}
...
//会员充1000返300
var vipPolicy_10=function(account,originTotal){
    if(account===0){
        account+=1300;
        return originTotal*0.9
    }else{
        account+=1300;
        return originTotal;
    }
    return originTotal-Math.floor(originTotal/200)*30
}
...
var vipPolicy_n=function(){
    ...
}
var getActualTotal=function(onSaleType,originTotal,account){
    switch(onSaleType){
        case 0:
            return vipPolicy_0(originTotal);
        case 1:
            return vipPolicy_0(originTotal);
        ...
        case n:
            return ...
        default:
            return originTotal;
    }
}
Copy after login
Copy after login

Okay, now each of our strategies has its own independent space. It seems Be well organized. But there are still two problems that have not been solved:

    With the increase of promotional strategies, the code volume of
  1. getActualTotal

    will still become larger and larger

  2. The system lacks flexibility. If you need to add a strategy, in addition to adding a strategy function, you also need to modify the
  3. switch...case..

    statement

  4. Let us review the definition of the strategy pattern:
定义一系列的算法,把它们一个个封装起来,并且使它们可互相替换

在我们的例子中,每种促销策略的实现方式是不一样的,但我们最终的目的都是为了求得实际金额。策略模式可以把我们对促销策略的算法一个个封装起来,并且使它们可互相替换而不影响我们对实际金额的求值,这正好是我们所需要的。

下面我们用策略模式来重构上面的代码:

var policies={
    "Type_0":function(originTotal){
        return originTotal-Math.floor(originTotal/100)*10 
    },
    "Type_1":function(originTotal){
        return originTotal-Math.floor(originTotal/200)*30 
    },
    ...
    "Type_n":function(originTotal){
        ... 
    }
}
var getActualTotal=function(onSaleType,originTotal,account){
    return policies["Type_"+onSaleType](originTotal,account)
}
//执行
getActualTotal(0,2680.00);//2208
Copy after login
Copy after login

分析上面的代码我们发现,不管促销策略如何增加,getActualTotal函数完全不需要再变化了。我们要做的,就是增加新策略的函数而已。

通过策略模式的代码,我们消除了让人反胃的大片条件分支语句,getActualTotal本身并没有计算能力,而是将计算全权委托给了策略函数。

由此我们可以总结出策略模式实现的要点:

  1. 将变化的算法封装成独立的策略函数,并负责具体的计算

  2. 委托函数,该函数接受客户请求,并将请求委托给某一个具体的策略函数

用一张UML图表示如下:
How to use the strategy pattern of design patterns in the front-end

怎么样?现在看到上面这张图是不是有了了然于胸的感觉?那就赶紧去试一试策略模式吧!

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样使用JS+H5实现微信摇一摇

如何对微信小程序进行开发

The above is the detailed content of How to use the strategy pattern of design patterns in the front-end. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!