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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
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. .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
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
- . . .
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
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:
定义一系列的算法,把它们一个个封装起来,并且使它们可互相替换
在我们的例子中,每种促销策略的实现方式是不一样的,但我们最终的目的都是为了求得实际金额。策略模式可以把我们对促销策略的算法一个个封装起来,并且使它们可互相替换而不影响我们对实际金额的求值,这正好是我们所需要的。
下面我们用策略模式来重构上面的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
分析上面的代码我们发现,不管促销策略如何增加,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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.
