Home Web Front-end JS Tutorial Javascript Strategy Pattern

Javascript Strategy Pattern

Mar 13, 2018 pm 05:44 PM
javascript js Strategy

This time I bring you Strategy Mode of Javascript, what are the Notes of Javascript Strategy Mode, the following is a practical case, let’s take a look .

The strategy pattern refers to defining a series of algorithms and encapsulating each algorithm so that they can be replaced with each other. The Strategy pattern allows the algorithm to change independently of the clients using it.

The strategy pattern uses technologies and ideas such as combination and delegation to avoid many if conditional statements

The strategy pattern provides an open-closed principle, making the code easier to understand and expand

Simple value

Many examples, using performance grade and salary to calculate bonuses as examples

let calculateBouns = (level,salary)=>{    if(level=='A'){        return salary * 1.4;
    }else if(level=='B'){        return salary * 1.3;
    }else if(level=='C'){        return salary * 1.2;
    }else{        return salary;
    }
}console.log(calculateBouns('A', 8000)); //11200console.log(calculateBouns('C', 8000)); //9600
Copy after login

Strategy mode reconstruction

//策略对象class ruleA{    calculate(salary){        return salary * 1.4;    }} class ruleB{    calculate(salary){        return salary * 1.3;    }} class ruleC{    calculate(salary){        return salary * 1.2;    }} //奖金类class Bouns{    constructor(){        this.salary = null;        this.level = null;    }    setLevel(level){        this.level = level;    }    setSalary(salary){        this.salary = salary;    }    getBouns(){        return this.level.calculate(this.salary);    }}let tom = new Bouns(),jerry = new Bouns();//设置薪资tom.setSalary(8000);jerry.setSalary(10000);//设置策略对象tom.setLevel(new ruleA());jerry.setLevel(new ruleA());console.log(tom.getBouns()); //11200console.log(jerry.getBouns()); //14000jerry.setLevel(new ruleB());console.log(jerry.getBouns()); //13000
Copy after login

Form

Another example of understanding the strategy pattern is Form validation, which usually involves multiple field validity judgments

let form = document.getElementById("Form");
form.onsubmit = function(){    if(form.username.value == ''){
        alert('用户名不能为空');        return false;
    }else if(form.username.value.length <= 6){
        alert(&#39;用户名长度不能小于6位&#39;);        return false;
    }else if(form.password.value.length <= 6){
        alert(&#39;密码长度不能小于6位&#39;);        return false;
    }else if(!/(^1[3|5|8][0-9]{9}$)/.test(form.phone.value)){
        alert("手机号码格式不正确");        return;
    }else{
        submit();
    }
}
Copy after login

Disadvantages of the code implemented in this way:

The function is bloated and contains a lot of if judgments

The function lacks flexibility and violates the open-closed principle

The function has poor reusability. If you add a form that requires similar verification, you can only copy it once

Strategy pattern implements form validation

// 策略对象let strategys = {    isEmpty: (value,errorMsg)=> {        if(value === &#39;&#39;) {            return errorMsg;
        }
    },    // 限制最小长度
    minLength: (value,length,errorMsg)=> {        if(value.length < length) {            return errorMsg;
        }
    },    // 手机号码格式
    illegalPhone: (value,errorMsg)=> {        if(!/(^1[3|5|8][0-9]{9}$)/.test(value)) {            return errorMsg;
        }
    } 
};class Validator{    constructor(){        this.cache = []; //保存校验规则
    }
    addRule(dom,rules){        var self = this;        for(let i = 0, rule; rule = rules[i++]; ){            let strategyAry = rule.strategy.split(":");            let errorMsg = rule.errorMsg;
            self.cache.push(function(){                let strategy = strategyAry.shift();
                strategyAry.unshift(dom.value);
                strategyAry.push(errorMsg);                return strategys[strategy].apply(dom,strategyAry);
            });
        }
    }
    check(){        for(let i = 0, fn; fn = this.cache[i++]; ) {            let msg = fn(); // 开始效验 并取得效验后的返回信息
            if(msg) {                return msg;
            }
        }
    }
}// 代码调用let form = document.getElementById("Form");let validateFunc = function(){    let validator = new Validator(); // 实例化Validator
    //添加一些校验规则
    validator.addRule(form.username,[
        {strategy: &#39;isEmpty&#39;,errorMsg:&#39;用户名不能为空&#39;},
        {strategy: &#39;minLength:6&#39;,errorMsg:&#39;用户名长度不能小于6位&#39;}
    ]);
    validator.addRule(form.password,[
        {strategy: &#39;minLength:6&#39;,errorMsg:&#39;密码长度不能小于6位&#39;},
    ]);
    validator.addRule(form.phone,[
        {strategy: &#39;illegalPhone&#39;,errorMsg:&#39;手机号格式不正确&#39;},
    ]);    return  validator.check();
};
form.onsubmit = function(){    let errorMsg = validateFunc();    if(errorMsg){
        alert(errorMsg);        return false;
    }else{
        submit();
    }
}
Copy after login

The strategy pattern belongs to the object behavior pattern. It mainly targets a set of algorithms and encapsulates each algorithm into an independent class with a common interface so that they can interact with each other. replace.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of JS inheritance

Node file batch renaming

The above is the detailed content of Javascript Strategy Pattern. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

exe to php: an effective strategy to achieve function expansion exe to php: an effective strategy to achieve function expansion Mar 04, 2024 pm 09:36 PM

EXE to PHP: An effective strategy to achieve function expansion. With the development of the Internet, more and more applications have begun to migrate to the web to achieve wider user access and more convenient operations. In this process, the demand for converting functions originally run as EXE (executable files) into PHP scripts is also gradually increasing. This article will discuss how to convert EXE to PHP to achieve functional expansion, and give specific code examples. Why Convert EXE to PHP Cross-Platformness: PHP is a cross-platform language

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Full analysis of CentOS7 software installation steps and strategies Full analysis of CentOS7 software installation steps and strategies Jan 04, 2024 am 09:40 AM

I started to officially come into contact with Linux in 2010. The entry-level distribution was Ubuntu10.10, and later transitioned to Ubunu11.04. During this period, I also tried many other mainstream distributions. After entering the laboratory, I started using CentOS5, then CentOS6, and now it has evolved to CentOS7. I have been using Linux for four years. The first three years were spent messing around, wasting a lot of time, and gaining a lot of experience and lessons. Maybe I am really old now and am no longer willing to bother with it. I just hope that after configuring a system, I can continue to use it. Why write/read this article? When using Linux, especially CentOS, you will encounter some pitfalls, or some things that people with mysophobia can't tolerate: software from official sources

See all articles