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

What is the Strategic pattern Strategy in JS and Design pattern

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces what is the strategic pattern Strategy in JS and design pattern, the content is very detailed, interested friends can refer to it, I hope it can be helpful to you.

First, an overall summary

1. The author talks about

Strategy pattern, also known as algorithm cluster pattern, defines different algorithms and can replace each other, which makes the change of the algorithm independent of the customers who use the algorithm.

The policy mode is similar to the factory mode in that it is relatively simple and easy to understand and can be switched freely at run time. The factory pattern focuses on creating objects.

Policy pattern is widely used, for example: we now want to define the data exchange format, the existing three schemes can be implemented using policy pattern.

What I want to emphasize here is that we choose different solutions for different data sources, and we all do the same operation with the same intention for the same thing, but with different solutions.

The code is implemented as follows:

Var dataSourceVendor = {xml: {get: function () {console.log ("XML data Source");}}, json: {get: function () {console.log ("JSON data Source") }, csv: {get: function () {console.log ("CSV data source");}; console.log ("selected data source:" + dataSourceVendor ["json"] ["get"] ())

Notice that their interfaces are the same, that is, they are intended to operate in the same way, but with different implementations.

Let's look at another example as follows:

The above example is not difficult to understand, when we send packages, we can choose what we think is convenient and quick, as customers are free to choose, but the intention remains the same what we do is to send packages, but the form is different.

Second, source code case reference

For example, in the name box, you need to verify that it is not empty, sensitive words, and characters are too long. Of course, you can write 3 if else to solve the problem, but the extensibility and maintainability of writing code in this way can be imagined.

If there are more elements in the form and there are more cases that need to be checked, it is not impossible to write hundreds of if else. So it is better to encapsulate each validation rule separately with a policy pattern.

When you need which kind of validation, you only need to provide the name of the policy. It's like this:

As you can see, various validation rules can be easily modified and replaced with each other. If the requirements change one day, it is recommended that the limit of too long characters be changed to 60 characters. I think I can finish the work soon.

Let's take another example:

If you have read the jQuery source code, you will not be unfamiliar with this code. Observe that they also have a common feature, that is, they all have the same interface and complete an intentional operation. The difference is that the value is taken in a different way, but it is a value operation.

This technique is called HOOHS in jQuery reference article: http://blog.rodneyrehm.de/archives/11-jQuery-Hooks.html

Third, the introduction of cases.

Var validator = {types: {}, messages: [], config: {}, validate:function (data) {var I, msg, type, checker, result_ok; this.messages = []; for (i in data) {if (data.hasOwnProperty (I)) {type = this.config [I] Checker = this.types [type]; if (! type) {continue } if (! checker) {throw {name: "ValidationError", message: "No handler to validate type" + type};} result_ok = checker.validate (data [I]) If (! result_ok) {msg = "Invalid value for *" + I + "*," + checker.instructions; this.messages.push (msg);} return this.hasErrors () }, hasErrors:function () {return this.messages.length! = = 0;}}; validator.types.isNonEmpty = {validate:function (value) {return value! = = "";}, instructions: "the value cannot be empty"} Validator.types.isNumber = {validate:function (value) {return! isNaN (value);}, instructions: "the value can only be a valid number, e.g. 1,3.14 or 2010"}; validator.types.isAlphaNum = {validate:function (value) {return! / [^ a-z0-9] / i.test (value) }, instructions: "the value can only contain characters and numbers, no special symbols"}; var data = {first_name: "Super", last_name: "Man", age: "unknown", username: "Olymo"}; validator.config = {first_name:'isNonEmpty', age:'isNumber', username:'isAlphaNum'} Validator.validate (data); if (validator.hasErrors ()) {console.log (validator.messages.join ("\ n"));}

Fourth, sum up.

The policy pattern belongs to the object behavior pattern, which mainly aims at a group of algorithms, encapsulating each algorithm into an independent class with a common interface, so that they can replace each other. The policy mode allows the algorithm to change without affecting the client. In general, the policy pattern is suitable for use when an application needs to implement a specific service or function, and the program can be implemented in multiple ways.

There are three objects in policy mode:

(1) Environment object: this class implements references to interfaces or abstract classes defined in abstract policies.

(2) Abstract policy object: it can be implemented by interface or abstract class.

(3) specific strategy object: it encapsulates different algorithms to achieve the same function.

Using the policy pattern to build the application, we can choose different algorithms to realize the function of the application according to the user configuration and other contents. The specific selection is made by environmental objects. In this way, the code confusion caused by the use of conditional statements can be avoided and the flexibility and organization of the application can be improved.

The focus of the policy pattern-the focus of the policy pattern is not how to implement algorithms, but how to organize and invoke these algorithms, so as to make the program structure more flexible, better maintainability and expansibility.

The equality of the algorithm-one of the great characteristics of the strategy pattern is the equality of each strategy algorithm. For a series of specific strategy algorithms, everyone's status is exactly the same, and it is precisely because of this equality that algorithms can be replaced with each other. All the strategy algorithms are independent and independent of each other in implementation.

So this series of policy algorithms can be described as follows: policy algorithms are different implementations of the same behavior.

Run-time policy * nature-during the run, the policy pattern can only use one specific policy implementation object at a time, although it can be dynamically switched between different policy implementations, but only one can be used at the same time.

Public behavior-it is common to see that all specific policy classes have some public behavior. At this point, you should put these public behaviors into the common abstract policy role Strategy class.

Of course, at this point, the abstract policy role must be implemented using the Java abstract class, not the interface. This is also a typical standard practice of centralizing code above the inheritance hierarchy.

About JS and what is the strategic pattern in the design pattern Strategy is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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