Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the Strategy pattern in javascript Design pattern

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to realize the strategic pattern in the javascript design pattern". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to realize the strategic pattern in the javascript design pattern".

one。 Cognitive strategy model

Definition of policy pattern: define a series of algorithms, encapsulate them one by one, so that they can directly replace each other.

Strategy pattern is the second design pattern commonly used in development. it is very common in development and consists of two parts. The first part is the strategy class, which encapsulates many specific and similar algorithms. The second part is the environment class, which accepts the customer request and then delegates the request to the policy class. The popular point is to store the functions of the same algorithm in a wrapper, and each function is taken out in the same way, which is called the strategy pattern. Let's take a closer look at the code implementation.

two。 Concrete realization and thought

If you need to implement a program for calculating employee bonuses, the performance is 4 times the base salary for S, 3 times for A, and so on, so we normally implement the code by judging branch statements.

1. Implemented by branching

Let bonus = function (performance, salary) {if (performance = "S") {return salary*4;} if (performance = "A") {return salary*3;} if (performance = "B") {return salary*2;}}

Analysis: this implementation has significant shortcomings, if with the expansion of performance, such as the increase of C _ Magi D _ (E), if branches continue to accumulate, making the code more and more large.

So we use the policy pattern to ReFactor the code.

two。 Using policy pattern to implement

Let performanceS = function () {}; performanceS.prototype.calculate = function (salary) {return salary*4} let performanceA = function () {}; performanceA.prototype.calculate = function (salary) {return salary*3} let performanceB = function () {} PerformanceB.prototype.calculate = function (salary) {return salary*2} let performanceC = function () {}; performanceC.prototype.calculate = function (salary) {return salary*1} let Bonus = function () {this.salary = null; / / original salary this.strategy = null / / original performance} Bonus.prototype.setSalary = function (salary) {this.salary = salary;} Bonus.prototype.setStrategy = function (strategy) {this.strategy = strategy;} Bonus.prototype.getBonus = function () {if (! this.strategy) {throw new Error ("performance not set") } return this.strategy.calculate (this.salary);} let bonus = new Bonus (); bonus.setSalary (10000); bonus.setStrategy (new performanceS ()); console.log (bonus.getBonus ())

Analysis: after refactoring, we put each performance algorithm into a separate function, and when we need to calculate a certain performance, we only need to transfer it into the getBonus function, remove the if branch, reduce the performance consumption, and make the code flexible, increase other performance at any time, and do not need to change the original code.

Main idea: this code is based on object-oriented language and introduces the concept of polymorphism, which is not suitable for js.

3. Policy mode of JavaScript version

Functions in / / js are also objects. Directly define strategy as functions let strategy = {"S": function (salary) {return salary*4;}, "A": function (salary) {return salary*3;}, "B": function (salary) {return salary*2 }} let calculateBonus = function (level, salary) {return strategy [level] (salary);} console.log (calculateBonus ('Aids, 20000)) / / 6000

Analysis: js objects can be created directly, encapsulating functions, so that the code is clear and concise. With the reuse of code, the flexibility becomes stronger.

The above is the main idea and implementation of js design pattern strategy pattern, it has two main functions in the application, one is to realize the sloshing animation of the strategy pattern, the other is to realize the form verification, the capable and interested friends can look down.

three。 The practical Application of Strategy Model

1. Using policy mode to implement cached animation

/ / slow algorithm let tween = {linear (t, b, c, d) {return c*t/d + b;}, easeIn (t, b, c, d) {return c * (t / = d) * t + b }, strongEaseIn (t, b, c, d) {return c * (t / = d) * t * t + b;}} / / define an animation class with the parameter let Animate = function (dom) {this.dom = dom; this.startTime = 0 of the dom node to be moved This.startPos = 0; this.endPos = 0; this.propertyName = null; this.easing = null; / / slow algorithm this.duration = null;} / / Startup method Animate.prototype.start = function (propertyName, endPos, duration, easing) {this.startTime = + new Date This.startPos = this.dom.getBoundingClientRect () [propertyName]; / / dom initial position this.propertyName = propertyName; this.endPos = endPos; this.duration = duration; this.easing = tween [easing]; let self = this Let timeId = setInterval (() = > {if (self.step () = false) {clearInterval (timeId);}}, 19);} / / realize what the ball does every frame Animate.prototype.step = function () {let t = + new Date If (t > this.startTime + this.duration) {this.update (this.endPos); return false;} let pos = this.easing (t-this.startTime, this.startPos, this.endPos-this.startPos, this.duration); this.update (pos) } Animate.prototype.update = function (pos) {this.dom.style [this.propertyName] = pos + 'px';} let test = function () {let div = document.getElementById (' div'); let animate = new Animate (div); animate.start ('left', 500,1000,' strongEaseIn') / / animate.start ('top', 1500,' strongEaseIn');} test ()

two。 Use policy mode for form validation

Let strategies = {isNonEmpty (value, errorMsg) {/ / determine whether if (value = =') {return errorMsg;}}, minLength (value, length, errorMsg) {if (value.length)

< length) { return errorMsg; } } } let dom = document.forms[0].acount; let validatarFunc = function () { let validator = new Validator(); // 添加校验规则 validator.add(dom, 'isNonEmpty', '用户名不能为空!'); let errorMsg = validator.start(); return errorMsg; // 返回校验结果 } // 实现表单校验保存类 let Validator = function () { this.cache = []; // 保存校验规则 } Validator.prototype.add = function (dom, rule, errorMsg) { let ary = rule.split(':'); this.cache.push( function(){ let strategy = ary.shift(); ary.unshift(dom.value); ary.push( errorMsg ); return strategies[strategy].apply(dom, ary); }) } Validator.prototype.start = function () { for(let i = 0, validatorFunc; validatorFunc = this.cache[i++];){ let msg = validatorFunc(); if( msg ) { return msg; } } } document.forms[0].addEventListener('submit', (e) =>

{let errorMsg = validatarFunc (); if (errorMsg) {alert (errorMsg); e.preventDefault ();}})

Analysis: the first implementation is to encapsulate the slow algorithm in an object so that it is easy to replace each other and expand when calling them.

The second implementation is to encapsulate the validation rules.

Thank you for your reading, the above is the content of "how to realize the strategic pattern in javascript design pattern". After the study of this article, I believe you have a deeper understanding of how to realize the strategic pattern in javascript design pattern, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report