The strategy mode of JavaScript design pattern

Source: Internet
Author: User

The so-called "all roads lead to Rome", in reality, in order to achieve a certain purpose is often not only one way. For example, earn money to support the family: can do a little business, can play a division of labor, and even can be stolen, Rob, gambling and other means. In programming language design, you will also encounter this similar situation, to achieve a function can have a variety of options. For example, on many map-based software, when you want to get to the B location from a location, you will be given several options for transportation, and you can see the cost and time required for each vehicle. In the programming language design, this kind of design pattern is called the strategy pattern.

definition of the policy pattern: The policy pattern refers to a series of algorithm definitions and encapsulates each algorithm, and allows them to be replaced with each other.

The main problem: in the case of multiple algorithms similar, the use of if...else is complicated and difficult to maintain.

As you can see from the above two points, the policy pattern is to eliminate the problem of nesting multiple layers of if...else statements by defining a series of algorithms and encapsulating them so that they can be replaced with each other. The definition of a series of algorithms here means that you can encapsulate each scheme as a function or as a form of a class.

Let's take a look at the output today is the day of the week example:

//gets the day of the week a few functionsfunctionGetDay (day) {if(Day = = 0) {Console.log (' Today is Sunday '); }                    if(Day = = 1) {Console.log (' Today is Monday '); }                    if(Day = = 2) {Console.log (' Today is Tuesday '); }                    if(Day = = 3) {Console.log (' Today is Wednesday '); }                    if(Day = = 4) {Console.log (' Today is Thursday '); }                    if(Day = = 5) {Console.log (' Today is Friday '); }                    if(Day = = 6) {Console.log (' Today is Saturday ');            }}; varDay =NewDate (). GetDay (); GetDay (day);

The code above is perfectly normal, and there is no problem with it, but it is not easy to maintain. Refactor the above code with the policy mode:

//Defining policy ClassesvarStrategies = (function(){                    functionA () {Console.log (' Today is Monday ');                    }; functionB () {Console.log (' Today is Tuesday ');                    }; functionC () {Console.log (' Today is Wednesday ');                    }; functionD () {Console.log (' Today is Thursday ');                    }; functionE () {Console.log (' Today is Friday ');                    }; functionF () {Console.log (' Today is Saturday ');                    }; functionG () {Console.log (' Today is Sunday ');                    }; return{getday1:a, getday2:b, Getday3:c, Getday4:d, Getday5:e, Getday6:f,            GETDAY0:G}) (); //A function that shows the day of the weekfunctionAlertweekday () {varD =NewDate (). GetDay ();     //Select the method that calls the strategies class according to the variable Dstrategies["GetDay" +d] ();};

Alertweekday ();

When you see this code, do you think the above code is more concise than the strategy model? From the point of view of code volume, this is true. But the reality is, as a developer we have 80% of the time to maintain the old code, the remaining 20% is to write new code, so it is also important to write maintainable code. The code after switching to policy mode has increased in code, but is easier to maintain. Why is it easier to maintain? If one day, the Getday () function of the date object is changed from 0~6 to Sunday (instead of the current 0 for Sunday, 1~6 respectively, Monday to Saturday), the first paragraph with if write code is to be used if the code of the structure to be changed again, But the second piece of code only needs to modify the method order of the return object in the Strategies class, which is easier to maintain at a glance.

Of course, the above is based on the object-oriented approach to the use of the policy model, we all know that JavaScript does not have the concept of class, so above is not the meaning of the JavaScript language policy pattern. In JavaScript, a function is a class-one object that can be passed into a function as a variable, so the JavaScript language is inherently self-contained in the policy pattern! Here's a look at the true JavaScript language policy pattern:

functionGetDay0 (e) {Console.log (' Today is Sunday: ' +e);}; functionGetDay1 (e) {Console.log (' Today is Monday: ' +e);}; functionGetDay2 (e) {Console.log (' Today is Tuesday: ' +e);}; functionGetDay3 (e) {Console.log (' Today is Wednesday: ' +e);}; functionGetDay4 (e) {Console.log (' Today is Thursday: ' +e);}; functionGetDay5 (e) {Console.log (' Today is Friday: ' +e);}; functionGetDay6 (e) {Console.log (' Today is Saturday: ' +e);}; //Show Memo event functionfunctionalertremindevents (FN, events) {fn (events);}; Alertremindevents (GetDay3,"My mother didn't have time to cook this afternoon, so I had to buy my own food and cook." ");

Advantages and disadvantages of the strategy model:

Advantages: 1, the algorithm can be switched freely. 2, avoid the use of multiple conditions to judge. 3, good Extensibility.

Disadvantages: 1, the strategy class will increase. 2. All policy classes need to be exposed externally.

The policy mode of JavaScript design 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.