How to use the strategy pattern of design patterns in the front-end
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:
10 off for purchases over 100
30 off for purchases over 200
50 off for purchases over 300
. . .
The interface of the cashier software is like this (simple illustration):
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
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:
Members recharge 300 and get 60, And the first single purchase is 10% off
Members recharge 500 and get 100 yuan back, and the first single purchase is 20% off
Members recharge 1,000 and the first single purchase is 7 Fold
...
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. .
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; } }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
getActualTotal
will still become larger and larger
- 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
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);//2208Analyzing 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.
getActualTotal itself has no computing power, but delegates the calculation to the strategy function.
- Encapsulate the changing algorithm into an independent strategy function and be responsible for the specific calculation
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 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:
"Design Patterns: ReusableObject-orientedBasics of Software"
《Dahua Design Pattern》
##《JavascriptDesign Pattern and Development Practice 》
- 10 off for purchases over 100
- 30 off for purchases over 200
- 50 off for purchases over 300
- . . .
//方便起见,我们把各个促销策略定义为枚举值: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); //2208The 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.
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:
- Members recharge 300 and get 60, And the first single purchase is 10% off
- Members recharge 500 and get 100 yuan back, and the first single purchase is 20% off
- Members recharge 1,000 and the first single purchase is 7 Fold
- ...
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; } }
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
- getActualTotal
will still become larger and larger
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:
定义一系列的算法,把它们一个个封装起来,并且使它们可互相替换
在我们的例子中,每种促销策略的实现方式是不一样的,但我们最终的目的都是为了求得实际金额。策略模式可以把我们对促销策略的算法一个个封装起来,并且使它们可互相替换而不影响我们对实际金额的求值,这正好是我们所需要的。
下面我们用策略模式来重构上面的代码:
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
分析上面的代码我们发现,不管促销策略如何增加,getActualTotal
函数完全不需要再变化了。我们要做的,就是增加新策略的函数而已。
通过策略模式的代码,我们消除了让人反胃的大片条件分支语句,getActualTotal
本身并没有计算能力,而是将计算全权委托给了策略函数。
由此我们可以总结出策略模式实现的要点:
将变化的算法封装成独立的策略函数,并负责具体的计算
委托函数,该函数接受客户请求,并将请求委托给某一个具体的策略函数
用一张UML图表示如下:
怎么样?现在看到上面这张图是不是有了了然于胸的感觉?那就赶紧去试一试策略模式吧!
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.