JavaScript design mode policy mode

Source: Internet
Author: User

In reality, we arrive at a place that can usually be chosen in different ways, such as bicycles, trains, cars, airplanes, etc.

In the program design, there will usually be such a situation, the implementation of a function has a number of options can be selected, such as a compressed file program, you can choose either the zip algorithm, or choose the gzip algorithm.

In this case, in design mode, it is called the policy mode.

The definition of a policy pattern: Define a series of algorithms, encapsulate them one by one, and make them interchangeable.

Example:

Many companies ' year-end awards are based on the employee's salary base and end-of-year performance. If the S-class performance is 4 times times the salary, a-level has 3 times times the salary, B level has twice times wages.

In situations where policy mode is not used, the code is typically designed like this:

varCalculatebonus =function(performancelevel,salary) {if(Performancelevel = = = "S"){            returnSalary * 4; }        if(Performancelevel = = = "A"){            returnSalary * 3; }        if(Performancelevel = = = "B"){            returnSalary * 2;    }    }; Calculatebonus ("B", 2000);//Output 4000Calculatebonus ("A", 2500);//Output 7500

It can be found that this code is very simple, but there are also a lot of problems.

The 1.calculateBonus function is quite large and contains a lot of if-else statements that need to cover all the logical branches.

2. Lack of elasticity, if you add performance level C, you need to drill down into the function internal modifications.

3. The reusability of the algorithm is poor, reuse can only be copied and pasted.

Refactor the code using the policy mode.

The policy mode of the program consists of at least two parts, the first part is the policy class, the policy class encapsulates the specific algorithm, and responsible for the specific calculation process. The second part is that the Environment class Context,context accepts the customer's request and delegates it to a policy class.

Now imitate the implementation of the policy pattern in the traditional object-oriented language:

//Defining policy Classes    varPerformances =function(){}; PerformanceS.prototype.calculate=function(Salary) {returnSalary * 4;    }; varPerformancea =function(){}; PerformanceA.prototype.calculate=function(Salary) {returnSalary * 3;    }; varPERFORMANCEB =function(){}; PerformanceB.prototype.calculate=function(Salary) {returnSalary * 2;    }; //Define Bonus Classes    varBonus =function(){         This. Salary =NULL;//Original Wages         This. Starategy =NULL;//the corresponding policy object    }; //Set up payrollBonus.prototype.setSalary =function(Salary) { This. Salary =salary;    }; //Set PerformanceBonus.prototype.setStrategy =function(strategy) { This. Strategy =strategy;    }; //Get bonusBonus.prototype.getBonus =function(){        return  This. Strategy.calculate ( This. Salary);    }; //Test    varBonus =NewBonus (); Bonus.setsalary (2000); Bonus.setstrategy (Newperformances); Console.log (Bonus.getbonus ())//Output 8000Bonus.setsalary (3000); Bonus.setstrategy (NewPERFORMANCEB); Console.log (Bonus.getbonus ())//Output 6000

In the example above, bonus acts as an environment class, delegating the client's request to one of the policy classes.

In JS, the actual can be more convenient practice, JS function is also an object, that is, functions can also be called as parameters.

 //Policy Classes    varPerformances =function(Salary) {returnSalary*4;    }; varPerformancea =function(Salary) {returnSalary*3;    }; varPERFORMANCEB =function(Salary) {returnSalary*2;    }; //Environment Class    varBonus =function(fn,salary) {returnfn (salary);    }; //TestConsole.log (Bonus (performances,1000));//Output 4000Console.log (Bonus (performanceb,3000));//Output 6000

Advantages and disadvantages of the strategy model:

Advantages:

1. Use combination, delegation, polymorphism and other techniques and ideas to avoid multiple conditional selection statements.

2. Easy to switch, understand, expand.

3. can be reused.

Disadvantages:

1. Having many policy classes or strategic objects is actually better than putting the logic of their responsibility in context.

2. Users should be aware of all the policy classes in order to select the most appropriate policy class.

Finally, a form validation is implemented through a policy pattern:

JavaScript design mode policy mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.