In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the TypeScript strategy model". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
I. what is the strategic model?
Definition: define a series of algorithms, encapsulate them one by one, and make them interchangeable.
A program based on policy pattern consists of at least two parts.
The first part is a set of policy class strategy, which encapsulates the specific algorithm and is responsible for the specific calculation process.
The second part is the environment class Context, where Context accepts the customer's request and then delegates the request to a policy class.
Second, the role of strategic model
In reality, there are many ways to reach the same destination in many cases. For example, if we want to travel to a certain place, we can choose the route according to the actual situation.
If you don't have time but don't care about money, you can choose to fly.
If you have no money, you can choose to take a bus or a train.
If you are poorer, you can choose to ride a bike.
Untitled Diagram.png
In programming, we often encounter a similar situation, in order to achieve a certain function, there are many options to choose. For example, a program that compresses files can choose either the zip algorithm or the gzip algorithm.
These algorithms are flexible and can replace each other at will. This solution is the policy pattern that will be introduced in this chapter.
Third, the case of strategic model
1. Calculate the bonus
Case description: a company's year-end bonus is based on the employee's salary base and year-end performance. For example, people with performance S get four times their year-end bonus, people with performance A get three times their year-end bonus, and people with performance B get twice their salary. The Finance Department asked us to provide a code to make it easier for them to calculate their employees' year-end bonus.
Calculate bonus: original version
Const calculateBouns = function (level: string,salary: number): number {if (level ='S') {return salary * 4;} if (level ='A') {return salary * 3;} if (level ='B') {return salary * 2;}} console.log (calculateBouns); / / output 16000 console.log (calculateBouns / / output 9000 console.log (calculateBouns ('Bogart 2000)); / / output 4000
* * Analysis * *:
The calculateBonus function is large and contains many if-else statements that need to cover all logical branches.
The calculateBonus function is inflexible, if a new performance level C is added, or if we want to change the bonus coefficient of performance S to 5, then we must go deep into the internal implementation of the calculateBonus function, which violates the open-closed principle.
The reusability of the algorithm is poor, what if these bonus algorithms need to be reused elsewhere in the program? Our choice is to copy and paste.
Calculate bonus: (using policy mode) object-oriented improved version
/ / calculate bonus: object-oriented improved version class PerformanceS {calculate (salary: number): number {return salary * 4}} class PerformanceA {calculate (salary: number): number {return salary * 3}} class PerformanceB {calculate (salary: number): number {return salary * 2} interface strategy {calculate: (salary: number) = > number;}
First create a bonus (Context) object and set some raw data to the bonus object, such as the employee's original salary.
Next, a policy object that calculates the bonus is also passed into the bonus object to save it.
When bonus.getBonus () is called to calculate the bonus, the bonus object itself does not have the ability to calculate
Instead, the request is delegated to a previously saved policy object:
/ / Context object class Bouns {public salary: number; / / original salary public strategy: strategy; / / the policy object setSalary (salary: number) {this.salary = salary corresponding to the performance level / / set the employee's original salary} setStrategy (strategy: strategy) {this.strategy = strategy / / set the policy object corresponding to the employee performance grade} getBouns () {/ / get the bonus amount return this.strategy.calculate (this.salary); / / delegate the operation of calculating the bonus to the corresponding policy object}} const bouns = new Bouns () Bouns.setSalary (4000); bouns.setStrategy (new PerformanceS ()); console.log (bouns.getBouns ()); / / output 16000 bouns.setSalary (3000); bouns.setStrategy (new PerformanceA ()); console.log (bouns.getBouns ()); / / output 9000 bouns.setSalary (2000); bouns.setStrategy (new PerformanceB ()); console.log (bouns.getBouns ()); / / output 4000
Let's review the idea of strategic patterns: define a series of algorithms, encapsulate them one by one, and make them interchangeable. To put this sentence in more detail, it is to define a series of algorithms and encapsulate them into policy classes, and the algorithms are encapsulated in methods within the policy class. When a customer initiates a request to Context, Context always delegates the request to one of these policy objects for calculation.
Calculating bonus: a perfect version of JavaScript
/ / calculate bonus: perfect version of JavaScript / / in JavaScript, functions are also objects, so it is easier and more straightforward to define strategy as a function interface strategy {S: (salary: number) = > number; A: (salary: number) = > number; B: (salary: number) = > number;} const strategy: strategy= {S: function (salary: number): number {return salary * 4 }, A: function (salary: number): number {return salary * 3;}, B: function (salary: number): number {return salary * 2;}} / / Context var calcluateBouns = function (level: string,salary: number): number {return strategy [level] (salary);} console.log (calcluateBouns ('Sylphology 4000)); / / output 16000 console.log (calcluateBouns / / output 9000 console.log (calcluateBouns ('Bogart 2000)); / / output 4000
2. Form validation
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
User name (verify that it is empty)
Password (authentication length cannot be less than 6 digits)
Mobile phone number (verify whether it is in mobile phone number format)
Form validation: original version
??? Please enter the user name: please enter the password:? Please enter your mobile phone number:? Submit? Var registerForm = document.getElementById ('registerForm');? registerForm.onsubmit = function () {? if (registerForm.userName.value = =') {? Alert ('user name cannot be empty');? Return false;?}? If (registerForm.password.value.length < 6) {? Alert ('password length cannot be less than 6 digits');? Return false;?}? If (! / (^ 1 [3 | 5 | 8] [0-9] {9} $) / .test (registerForm.phoneNumber.value)) {? Alert ('incorrect mobile phone number format');? Return false;?}?}?
Analysis:
The registerForm.onsubmit function is large and contains many if-else statements that need to override all the validation rules.
The registerForm.onsubmit function is inflexible. If a new verification rule is added, or if we want to change the length check of the password from 6 to 8, we must go deep into the internal implementation of the registerForm.onsubmit function, which violates the open-closed principle.
The reusability of the algorithm is poor, if another form is added to the program, and this form also needs some similar verification, then we are likely to copy these check logic all over the world.
Form validation: a case of Policy pattern
/ / Policy object const strategies: Object = {isEmpty (value: string, errMsg: string): string {if (value =') {return errMsg}}, minLength (value: string, length: number, errMsg: string): string {if (value.length {const strategy: string = params.shift (); params.unshift (value); params.push (msg)) Return strategies [strategy] .apply (null, params)} check (): string {let value: Function; for (value of this.cache) {const msg = value (); if (msg) {return msg} var submitBtn = document.getElementById ('submitBtn') Var registerForm = document.getElementById ('registerForm'); var validateFunc = function () {var validator = new Validator (); / / add rule validator.add (registerForm.username.value,'isEmpty',' username cannot be empty'); validator.add (registerForm.password.value,'minLength:6',' password length cannot be less than 6 digits'); validator.add (registerForm.phone.value,'isMobile',' mobile phone number is not in correct format') / / check result var errMsg = validator.check (); return errMsg;} submitBtn.onclick = function () {var errMsg = validateFunc (); if (errMsg) {console.log (errMsg); return false;} else {console.log ('form successful')}}
Fourth, the advantages and disadvantages of the strategy model
Advantages:
By using the techniques and ideas of combination, delegation and polymorphism, the strategy model can effectively avoid multiple conditional selection statements.
The policy pattern provides perfect support for the open-closed principle, encapsulating the algorithms in independent strateg (policies), making them easy to switch, easy to understand, and easy to expand.
Algorithms in the policy pattern can also be reused elsewhere in the system, avoiding a lot of repetitive copy-and-paste work.
Using composition and delegation in policy mode to give Context the ability to execute algorithms is also a lighter alternative to inheritance.
Disadvantages:
1. Using the policy pattern will add a lot of policy classes or policy objects to the program, but in fact this is better than stacking the logic they are responsible for in Context.
2. To use the policy mode, you must understand all the strategy and the differences between each strategy so that you can choose an appropriate strategy. For example, if we want to choose a suitable travel route, we must first understand the details of choosing airplanes, trains, bicycles and so on. At this point, strategy has to expose all its implementations to the customer, which violates the principle of least knowledge.
This is the end of the content of "what is the TypeScript Strategy Mode". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.