One, general overview
1, the author discusses
The strategy pattern, also called the algorithm cluster pattern, is to define the different algorithms, and can replace each other, this pattern makes the algorithm changes independently of the customers using the algorithm.
The strategy mode and the factory model are similar, the strategy mode is relatively simple and easy to understand, and can be switched freely at the time of operation. The Factory mode focus is to create objects.
The strategy mode is widely used, for example: We are now going to define the data Interchange format, the existing three kinds of options 1,xml 2,json 3,csv can be implemented using the policy mode.
What I would like to emphasize here is that------ we choose different scenarios for different data sources, it's all about the same thing with the same intent, but the scenario is different.
The code is implemented as follows:
1 varDatasourcevendor = {2 xml: {3Get:function(){4Console.log ("XML Data Source") ;5 }6 } ,7 JSON: {8Get:function(){9Console.log ("JSON data source") ;Ten } One } , A csv: { -Get:function(){ -Console.log ("CSV data source") ; the } - } - } ; -Console.log ("Selected data source:" + datasourcevendor["json"] ["get"] ());
Notice that their interfaces are consistent, that is, the intent to operate the same, but the implementation is different.
Let's look at an example like this:
The above example is not difficult to understand, we in the delivery of the package can choose their own convenient and quick way, as the customer is free to choose the way, but the intention is still the same thing we do is to send the package, but the form is different.
Second, source case reference
For example, in the Name box, you need to verify the non-empty, sensitive words, characters too long in several cases. Of course, you can write 3 if else to solve, but so the code extensibility and maintainability is conceivable.
It is not impossible to add up hundreds if else if there are more elements in the form that need to be verified. So a better approach is to encapsulate each validation rule in a separate policy pattern.
You only need to provide the name of the policy when you need to verify it. just like this:
As you can see, various validation rules are easily modified and replaced with each other. If one day the requirement changes, it is recommended that the limit for the long character be changed to 60 characters. I think I'll be able to finish this work soon.
Let's look at an example:
This code if you read the jquery source of the people will not be unfamiliar, observe that they also have a common denominator is the interface is consistent, the completion is a kind of intent operation, the difference is to take the value of different ways, but are the value operation.
This technique is referred to in jquery as the hook mechanism (HOOHS) reference article: http://blog.rodneyrehm.de/archives/11-jQuery-Hooks.html
Third, the introduction of the case
1 varValidator = {2 3 types:{},4 5 messages:[],6 7 config:{},8 9Validatefunction(data) {Ten varI, MSG, type, checker, RESULT_OK; One This. Messages = []; A for(Iinchdata) { - if(Data.hasownproperty (i)) { -Type = This. Config[i]; theChecker = This. Types[type]; - if(!type) { - Continue; - } + if(!checker) { - Throw { +Name: "ValidationError", AMessage: "No handler to validate type" +type at }; - } -RESULT_OK =checker.validate (Data[i]); - if(!RESULT_OK) { -msg = "Invalid value for *" + i + "*," +checker.instructions; - This. Messages.push (msg); in } - } to } + return This. HasErrors (); - }, theHasErrors:function () { * return This. messages.length!== 0; $ }Panax Notoginseng }; - theValidator.types.isNonEmpty = { +Validatefunction(value) { A returnValue!== ""; the }, +Instructions: "The value cannot be empty" - }; $ $Validator.types.isNumber = { -Validatefunction(value) { - return!IsNaN (value); the }, -Instructions: "The value can only be a valid number, e.g. 1, 3.14 or 2010"Wuyi }; the -Validator.types.isAlphaNum = { WuValidatefunction(value) { - return!/[^a-z0-9]/i.test (value); About }, $Instructions: "The value can only contain characters and numbers, no special symbols" - }; - - vardata = { AFirst_Name: "Super", +Last_Name: "Man", theAge: "Unknown", -Username: "O_o" $ }; theValidator.config = { theFirst_Name: ' Isnonempty ', theAge: ' Isnumber ', theUsername: ' Isalphanum ' - }; in validator.validate (data); the if(Validator.haserrors ()) { theConsole.log (Validator.messages.join ("\ n")); About}
Four, summarize
The policy pattern belongs to the object behavior pattern, which is mainly for a set of algorithms, encapsulating each algorithm in a separate class with a common interface, so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client. Typically, a policy pattern is used when an application needs to implement a particular service or feature, and the program is implemented in a variety of ways.
There are three objects in the policy mode:
(1) Environment object: a reference to an interface or abstract class defined in an abstract policy is implemented in this class.
(2) Abstract policy object: it can be implemented by an interface or an abstract class.
(3) Specific policy object: it encapsulates different algorithms for implementing the same function.
Using the policy model to build the application, you can choose different algorithms to implement the functions of the application according to the user configuration and other content. The specific selection has the environment object to complete. This approach avoids the code clutter caused by the use of conditional statements, improving application flexibility and rationality.
The center of gravity of the policy pattern------ The focus of the strategy pattern is not how to implement the algorithm, but how to organize, call these algorithms, so that the program structure more flexible, with better maintainability and extensibility.
The equality of the algorithm------ Strategy mode is one of the most important features is the equality of each strategy algorithm. For a series of specific strategy algorithms, everyone's status is exactly the same, because of this equality, can be achieved between the algorithm to replace each other. All strategy algorithms are independent of each other in implementation, and are not dependent on each other.
So you can describe this series of strategy algorithms: Policy algorithms are different implementations of the same behavior.
the uniqueness of the run-time policy------ during the run, the policy mode can only use one specific policy implementation object at a time, although it is possible to dynamically switch between different policy implementations, but only one can be used at the same time.
public behavior------ often see that all specific policy classes have some public behavior. At this time, the public behavior should be put into the common abstract strategy role strategy class inside.
Of course, abstract policy roles must be implemented in Java abstract classes, not interfaces. This is also a typical standard practice of centralizing the code to inherit hierarchy.
hahaha, the end of this article, not to be continued, hope and we have enough communication, common progress (*^__^*) call ...
Big Xun Jun talk about JS and design mode of------Strategy mode strategy