Strategy pattern: Define a set of algorithms, encapsulate them one by one, and make them interchangeable
Life chestnut: Zhuge tips
Zhuge to Liu Bei’s nostrum, encounter any difficulties have to deal with the plan. The policy pattern implements a similar scenario.
Another chestnut: to like the girl to buy ice cream, do not know their preferences in advance, can only collect all kinds of flavor, always hit. The downside of strategic models is that they are “expensive” and need to think through all the scenarios beforehand.
Model features
- Policy class: The algorithm is encapsulated as a separate function/object
- Environment class: call the corresponding policy function/object to execute according to different parameters
Pattern implementation
Implementation: A program based on strategy pattern is composed of at least two parts. The first part is a set of Strategies (variable), which encapsulates class-specific algorithms and is responsible for the specific calculation process. The second part is the environment class Context (unchanged), which receives the client’s request and then delegates it to a policy class.
Suppose we have a development team, consisting of (development lead, back end, front end, test). The development lead gets the development task (unchanged), but the specific task executor can be divided by type (variable).
For example, there are several development tasks:
- Tuning the server cache (back-end tasks)
- Optimize the loading speed of the first screen (front-end task)
- Complete system concurrent tests (test tasks)
The development team leader will distribute the tasks to the corresponding developers according to the task type. The team leader does not undertake specific development tasks. So each developer assumes the role of Strategy (independent task execution), while the leader owns and directs all developer resources and acts as the Context. Each developer on the team ** “combines” ** into a Strategies class (performing development tasks). This strategy is variable. If subsequent development tasks require android and IOS support, just add Android and IOS developer configuration (extensible).
Var Strategies = {"backend": function(task) {
console.log('Performing back-end tasks:', task);
},
"frontend": function(task) {
console.log('Perform front-end tasks:', task);
},
"testend": function(task) {
console.log('Perform a test task:', task); }}; // Environment class (development team leader) var Context =function(type, task) {
typeof Strategies[type= = ='function' && Strategies[type](task);
}
Context('backend'.'Optimize server cache');
Context('frontend'.'Optimize home page loading speed');
Context('testend'.'Complete system concurrent tests');
Copy the code
The benefits of the above code:
- Algorithm independent encapsulation, task distribution; The development leader does not undertake specific development tasks (only doing top-level design, not competing with young people for jobs)
- Better reusability, not limited to Context calls; Developers need to get hired (write code wherever you go)
Another benefit of the strategy pattern is that it eliminates most of the if… else / switch… Case conditional branch statement, code reading improved.
// Group leader without policy mode... var Context =function(type, task) {
if (type= = ='backend') {// Call me the back end}else if (type= = ='frontend') {// Call me the front end}else if (type= = ='testend') {// Call me the test}}Copy the code
In JavaScript, functions are treated as “first-class citizens”, also known as “first-class objects”. In JavaScript “higher-order function” applications, functions can be passed or called as variables or arguments. So in JavaScript, we can wrap an algorithm into a separate function and pass it as an argument to another function call.
// Encapsulate a separate function var backend =function(task) {
console.log('Performing back-end tasks:', task);
};
var frontend = function(task) {
console.log('Perform front-end tasks:', task);
};
var testend = function(task) {
console.log('Perform a test task:', task); }; // Environment class (development team leader) var Context =function(func, task) {
typeof func === 'function' && func(task);
}
Context(backend, 'Optimize server cache');
Context(frontend, 'Optimize home page loading speed');
Context(testend, 'Complete system concurrent tests');
Copy the code
Without the outer layer of Strategies, functions are more independent and do not prevent them from being called. Using functions instead of policy classes is the “invisible” policy pattern we often use in daily development.
Applicable scenario
- Multiple conditional statement judgment, the implementation of the corresponding algorithm scene
- Form validator
The advantages and disadvantages
- Advantages:
- Use the techniques and ideas of composition, delegation and polymorphism to avoid multiple conditional selection statements
if... else/switch... case
; - The algorithm function can be used in other parts of the system.
- Support design pattern “development-closed principle”, algorithm encapsulation in an independent Strategy, easy to maintain and expand;
- The policy pattern uses “composition and delegation” to give the Context the ability to execute the algorithm, a possible alternative to object inheritance
- Use the techniques and ideas of composition, delegation and polymorphism to avoid multiple conditional selection statements
- Disadvantages:
- Added many policy classes or objects (clearly defined developer functions and increased personnel costs);
- It is necessary to understand the differences of each Strategy and violate the “least knowledge principle” (the team leader has corresponding developers under his supervision so as not to be so helpless and painful).
Refer to the article
- JavaScript Design Patterns
- JavaScript Design Patterns and Development Practices
- Explanation and Application of JavaScript Design Pattern System
Github is looking forward to Star! Github.com/ZengLingYon…
Author: in the name of music this article is original, there are inappropriate places welcome to point out. Reprint please indicate the source.