JS and design pattern ------ Strategy pattern Strategy

Source: Internet
Author: User

JS and design pattern ------ Strategy pattern Strategy
I. general summary 1. I talk about the policy mode, also known as the algorithm cluster mode, which defines different algorithms and can replace them with each other, this mode makes the algorithm changes independent of the customers who use the algorithm. The policy mode is similar to the factory mode. The policy mode is relatively simple and easy to understand, and can be switched freely at runtime. The factory mode focuses on creating objects. The policy mode is widely used. For example, to define the data exchange format, you can use the policy mode to implement the following three methods: 1, XML 2, JSON 3, and CSV. Here I want to emphasize that ------ we select different solutions for different data sources, and the operations for the same thing with the same intent are only different solutions. The code implementation is as follows: 1 var performancevendor = {2 xml: {3 get: function () {4 console. log ("XML data source"); 5} 6}, 7 json: {8 get: function () {9 console. log ("JSON data source"); 10} 11}, 12 csv: {13 get: function () {14 console. log ("CSV data source"); 15} 16} 17}; 18 console. log ("Selected Data source:" + performancevendor ["json"] ["get"] (); note that their interfaces are consistent, that is, the intent operation is consistent, but the implementation is different. Let's take a look at the following example: the above example is not hard to understand. We can choose a convenient and convenient method when sending a package, as the customer can choose freely, but what we do with the same intent is to send the package, but the form is different. 2. For source code case reference, for example, in the Name box, it is necessary to verify non-null, sensitive words, and long characters. Of course, three if else codes can be written, but the scalability and maintainability of codes can be imagined. If there are more elements in the form, there are more verification cases. It is not impossible to add up to hundreds of if else statements. Therefore, it is better to encapsulate each verification rule in a policy mode. You only need to provide the name of the policy for which authentication is required. As you can see, various verification rules are easily modified and replaced. If the requirement changes in the day, we recommend that you change the character length to 60 characters. I want to finish this job soon. Let's take another example: if anyone who has read the jQuery source code is familiar with this code, it also has a common feature that the interfaces are consistent, and the Operations completed are all intentional operations, the difference is that values are operated in different ways. This technique is called HOOHS in jQuery. reference article: http://blog.rodneyrehm.de/archives/11-jQuery-Hooks.html 3, the case introduces 1 var validator = {2 3 types: {}, 4 5 messages: [], 6 7 config :{}, 8 9 validate: function (data) {10 var I, msg, type, checker, result_ OK; 11 this. messages = []; 12 for (I in data) {13 if (data. hasOwnProperty (I) {14 type = this. config [I]; 15 checker = this. types [type]; 16 if (! Type) {17 continue; 18} 19 if (! Checker) {20 throw {21 name: "ValidationError", 22 message: "No handler to validate type" + type23}; 24} 25 result_ OK = checker. validate (data [I]); 26 if (! Result_ OK) {27 msg = "Invalid value for *" + I + "*," + checker. instructions; 28 this. messages. push (msg); 29} 30} 31} 32 return this. hasErrors (); 33}, 34 hasErrors: function () {35 return this. messages. length! = 0; 36} 37}; 38 39 validator. types. isNonEmpty = {40 validate: function (value) {41 return value! = ""; 42}, 43 instructions: "the value cannot be empty" 44}; 45 46 validator. types. isNumber = {47 validate: function (value) {48 return! IsNaN (value); 49}, 50 instructions: "the value can only be a valid number, e.g. 1, 3.14 or 2010 "51}; 52 53 validator. types. isAlphaNum = {54 validate: function (value) {55 return! /[^ A-z0-9]/I. test (value); 56}, 57 instructions: "the value can only contain characters and numbers, no special symbols" 58}; 59 60 var data = {61 first_name: "Super", 62 last_name: "Man", 63 age: "unknown", 64 username: "o_O" 65}; 66 validator. config = {67 first_name: 'isnonempty', 68 age: 'isnumber', 69 username: 'isalphanum '70}; 71 validator. validate (data); 72 if (validator. hasErrors () {73 console. log (validator. Messages. join ("\ n"); 74} 4. The rule mode is an object behavior mode. It is mainly used for a group of algorithms, encapsulate each algorithm into an independent class with a common interface so that they can be replaced with each other. The policy mode allows the algorithm to change without affecting the client. Generally, the policy mode is applicable when an application needs to implement a specific service or function, and the program has multiple implementation methods. There are three objects in the Policy mode: (1) environment object: This class implements reference to the interface or abstract class defined in the abstract policy. (2) Abstract policy object: it can be implemented by interfaces or abstract classes. (3) specific policy object: it encapsulates different algorithms that implement the same functionality. Using policy mode to build applications, you can select different algorithms based on user configurations to implement the functions of the applications. Select an environment object. This method can avoid code confusion caused by the use of conditional statements and improve the flexibility and organization of applications. The focus of the policy model ------ the focus of the policy model is not how to implement algorithms, but how to organize and call these algorithms to make the program structure more flexible, with better maintainability and scalability. Equality of algorithms-a major feature of the policy model is the equality of each policy algorithm. For a series of specific policy algorithms, everyone has the same status. Because of this equality, algorithms can be replaced with each other. All policy algorithms are independent of each other and are independent from each other. So we can describe this series of policy algorithms as follows: Policy algorithms are different implementations of the same behavior. The uniqueness of the runtime policy ------ during the runtime, the policy mode can use only one specific policy to implement the object at each moment, although it can be dynamically switched in different policy implementations, however, you can only use one. Public Behavior ------ it is often seen that all specific policy classes have public behaviors. At this time, these public behaviors should be put into the Strategy class of the common abstract policy role. Of course, at this time, the abstract policy role must be implemented using a Java Abstract class, rather than an interface. In fact, this is also a typical standard practice of inheriting code to the top of the hierarchy.

Related Article

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.