Design Pattern-strategy pattern, design pattern-strategy

Source: Internet
Author: User

Design Pattern-strategy pattern, design pattern-strategy

Rule ModeDefines a series of algorithms, encapsulates each algorithm, and enables them to replace each other. The rule mode allows algorithms to change independently of customers who use it.

  • Abstract policy role: a policy class, usually implemented by an interface or abstract class.
  • Specific policy roles: encapsulate related algorithms and behaviors.
  • Environment role: Hold a reference to the policy class and call it to the client.

Applicability:

• Many related classes only have different behaviors. "Policy" provides a method to configure a class with one of multiple actions. That is, a system must dynamically select one of several algorithms.
• Different variants of an algorithm are required. For example, you may define algorithms that reflect different space/time trade-offs. When these variants are implemented as class layers of an algorithm, the policy mode can be used.
• Algorithms use data that customers should not know. Policy modes can be used to avoid exposing complex algorithm-related data structures.
• A class defines multiple behaviors, which appear in the form of multiple conditional statements in the operations of this class. Move related condition branches into their respective Strategy classes to replace these condition statements.

The following is a simple case

Example:

Liu Bei is about to marry his wife in Jiangdong. Zhuge Liang gave Zhao Yun (Best Man) three tips before, saying that they had taken the opportunity to solve the difficult problem. Hey, don't say that it really solved the big problem, at the end, Zhou Yu joined his wife and gave up again. Let's take a look at what the scene looks like. Let's first talk about the elements in this scenario: three tips, one tip, and one Zhao Yun. The tips are given by Comrade Xiao Liang. They are placed in the tips, which are commonly known as tips, then Zhao Yun is a working person. How can he use a JAVA program to show his tricks, execute the tricks, and win the game? Let's first look at the class diagram:

If the three tips are of the same type, you can write an interface:

Package com. oumyye. rule mode;/*** @ author * I'm gglad to share my knowledge with you all. * First, define a policy interface, this is the three clever interfaces Zhuge Liang gave to Zhao Yun. **/public interface IStrategy {// each clever trick is an executable algorithm public void operate ();}

Then write three more implementation classes. There are three tips:

One

Package com. oumyye. rule mode;/*** @ author * I'm gglad to share my knowledge with you all. * Ask Joe to help, so Sun Quan cannot kill Liu Bei */public class BackDoor implements IStrategy {public void operate () {System. out. println ("Ask Qiao Guoluo for help and ask Wu Guotai to put pressure on Sun Quan ");}}

Two

Package com. oumyye. rule mode;/*** @ author * I'm gglad to share my knowledge with you all. * ask Wu Guotai for a green light */public class GivenGreenLight implements IStrategy {public void operate () {System. out. println ("ask Wu Guotai to open a green light and let it go! ");}}

Three

Package com. oumyye. rule mode;/*** @ author * I'm gglad to share my knowledge with you all. * After Mrs sun is disconnected, the defender */public class BlockEnemy implements IStrategy {public void operate () {System. out. println ("when Mrs sun is disconnected, block the pursuit of troops ");}}

Well, let's take a look. There are three tips. You need to put these tips and tips:

Package com. oumyye. rule mode;/*** @ author * I'm gglad to share my knowledge with you all. * if there is a strategy, there will also be a tip */public class Context {// constructor. You need to use that recipe private IStrategy straegy; public Context (IStrategy strategy) {this. straegy = strategy;} // The strategy is used. I have recruited public void operate () {this. straegy. operate ();}}

Then Zhao yunxiongyi carried three tips and pulled Liu's father, who had entered the ranks of the elderly and wanted to marry a pure girl, to settle for the family. Hi, don't say that, xiao Liang's three tips are really good:

Package com. oumyye. rule mode;/*** @ author */public class ZhaoYun {/*** Zhao Yun appeared. According to Zhuge Liang, split the first System in turn */public static void main (String [] args) {Context context; // when Wu Guo just arrived. out. println ("----------- remove the first -------------") When I arrived at Wu Guo; context = new Context (new BackDoor (); // get the context. operate (); // disassemble and execute System. out. println ("\ n"); // Liu Bei is happy and has removed the second System. out. println ("----------- Liu Bei is happy, Split the second one ------------- "); context = new Context (new GivenGreenLight (); context. operate (); // executes the second tip of the System. out. println ("\ n"); // What should I do? Remove the third System. out. println ("----------- Sun Quan's soldier chased it. What should I do? Split the third ------------- "); context = new Context (new BlockEnemy (); context. operate (); // Mrs sun withdraws from the System. out. println ("\ n");/** the problem is: Zhao Yun does not know the policy, he only knows how to split the first tip, but does not know what it is about BackDoor? * It seems that the Strategy name has been written in this mode. ** the error message is displayed! BackDoor, GivenGreenLight, and BlockEnemy are just a code. You write them as first, second, and * third. No one will say you are wrong! ** The advantage of the Policy mode is that it reflects the features of high cohesion and low coupling. The disadvantage is that I will go back and check it again */}}

With these three moves, Zhou Lang is "helping his wife fold again! This is the rule mode, and the features of high cohesion and low coupling are also shown. Another is scalability, that is, the OCP principle. The policy class can be added as long as the Context is modified. java is enough. I will not talk about this much. Let's understand it.

Advantages of the Policy mode:
  • The related algorithm series Strategy class levels define a series of reusable algorithms or actions for Context. Inheritance helps to analyze the common functions of these algorithms.
  • It provides a way to replace the inheritance relationship: inheritance provides another way to support multiple algorithms or actions. You can directly generate a subclass of the Context class to give it different behaviors. However, this will combine the implementation of the algorithm with the implementation of the Context to make the Context difficult to understand, maintain, and expand, in addition, algorithms cannot be dynamically changed. Finally, you get a bunch of related classes. The only difference between them is the algorithm or behavior they use. Encapsulate an algorithm in an independent Strategy class so that you can change it independently of its Context, making it easy to switch, understand, and expand.
  • Some if else condition statements are eliminated: The Strategy mode provides an option other than the action needed to select with the condition statement. When different behaviors are stacked in a class, it is difficult to avoid using conditional statements to select appropriate behaviors. Encapsulate behaviors in independent Strategy classes to remove these conditional statements. Code that contains many conditional statements usually means that the Strategy Mode is required.
  • The Strategy Mode can provide different implementations of the same behavior. Customers can choose from different policies based on different time/space trade-offs.

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.