Definition: Define a set of algorithms, encapsulate each algorithm, and make them interchangeable.
Type: Behavioral Pattern
Class diagram:
The policy pattern is the encapsulation of algorithms, encapsulating a series of algorithms into corresponding classes, and these classes implement the same interface and can be replaced by each other. In the behavioral class mode mentioned above, there is a pattern that also focuses on the encapsulation of the algorithm - the template method mode. Compared with the class diagram, you can see that the difference between the policy mode and the template method mode is only that there is a separate encapsulation class Context. The difference between it and the template method mode is: in the template method mode, the main body of the calling algorithm is in the abstract parent class, while in the strategy mode, the main body of the calling algorithm is encapsulated into the encapsulation class Context. Abstract strategy Strategy is generally an interface, the purpose is only to define the specification, and generally does not contain logic. In fact, this is just a general implementation. In actual programming, because there is inevitably some same logic between each specific strategy implementation class, in order to avoid duplicate code, we often use abstract classes to play the role of Strategy and encapsulate public code. Therefore, in many application scenarios, the shadow of the template method pattern is generally seen in the strategy mode.
Structure of policy patterns
Encapsulation class: also known as context, secondary encapsulation of policies is to avoid direct calls to policies by high-level modules.
Abstract strategy: Usually an interface. When there is duplicate logic in each implementation class, abstract classes are used to encapsulate this part of the common code. At this time, the policy pattern looks more like the template method pattern.
Specific strategy: Specific strategy roles are usually performed by a set of classes encapsulated with algorithms, and these classes can be replaced freely as needed.
Examples of application scenarios:
Liu Bei is going to marry his wife in Jiangdong. Before leaving, Zhuge Liang gave Zhao Yun (the best man) three tricks, saying that it would solve the difficult problem by disassembling it according to the secret of heaven. Hey, let's say, it really solved the big problem. In the end, Zhou Yu accompanied his wife and then broke his troops. Let's first see what this scene looks like.
Let’s first talk about the elements in this scene: three clever tricks, one clever trick, and one clever trick. The clever trick was given by Brother Liang. The clever trick is commonly known as the clever trick. Then Zhao Yun is a worker who takes out the clever trick, executes it, and then wins. How to express these with Java programs?
Let's take a look at the picture first?
The three tricks are the same type of things, so let's write an interface:
package com.yangguangfu.strategy; /** * * @author [email protected]: Afu* First define a strategy interface, which is the interface of the three tricks that Zhuge Liang gave to Zhao Yun. */ public interface IStrategy { //Every trick is an executable algorithm. public void operate(); }
Then write three implementation classes, there are three clever tricks:
A clever plan: First arrival in Wu:
package com.yangguangfu.strategy; /** * * @author [email protected]: A Fu* Ask for Mr. Qiao to help, so that Sun Quan cannot kill Liu Bei. */ public class BackDoor implements IStrategy { @Override public void operate() { System.out.println("Seeking old Qiao Guo's help, let Wu Guotai put pressure on Sun Quan so that Sun Quan cannot kill Liu Bei..."); } }
The second trick: Please give Wu Guotai a green light and let it go:
package com.yangguangfu.strategy; /** * * @author [email protected]: A Fu* Please give Wu Guotai a green light. */ public class GivenGreenLight implements IStrategy { @Override public void operate() { System.out.println("Please give Wu Guotai a green light, let it go!"); } }
Skill 3: Mrs. Sun cuts off the rear and blocks the pursuers:
package com.yangguangfu.strategy; /** * * @author [email protected]: Afu* Mrs. Sun cut off the rear and blocked the pursuers. */ public class BlackEnemy implements IStrategy { @Override public void operate() { System.out.println("Mrs. Sun cuts off the back, blocks the pursuers..."); } }
Okay, everyone, there are three tricks, so there is a place to put them in the tip:
package com.yangguangfu.strategy; /** * * @author [email protected]:Afu* */ public class Context { private IStrategy strategy; //Constructor, which trick do you want to use public Context(ISTRATEgy strategy){ this.strategy = strategy; } public void operate(){ this.strategy.operate(); } }
Then Zhao Yun was carrying three tips with great courage, pulling the old man Liu Bei, who had already entered the ranks of the elderly and wanted to marry a innocent girl, went to marry into his wife. Hi, let alone, Brother Liang’s three tricks are really good. Look:
package com.yangguangfu.strategy; public class ZhaoYun { /** * Zhao Yun appeared. According to Zhuge Liang's explanation to him, he took apart the tricks in turn*/ public static void main(String[] args) { Context context; // When I first arrived in Wu, I disassembled the first System.out.println("------------------------------------------"); context = new Context(new BackDoor()); context.operate();//Execute System.out.println("/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n"); //When Liu Bei was happy to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwilling to be unwill Disassemble the third tip System.out.println("--------------------------------------------------"); context = new Context(new BlackEnemy()); context.operate();// Disassemble and execute System.out.println("/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/
Advantages and Disadvantages of Policy Mode The main advantages of Policy Mode are:
Policy classes can be switched freely, and since policy classes implement the same abstraction, they can be switched freely.
Easy to expand, adding a new policy is very easy for the policy model, and it can basically be expanded without changing the original code.
Avoid using multiple conditions. If you do not use the policy mode, for all algorithms, conditional statements must be used to connect, and the algorithm to be used through conditional judgment. In the previous article, we mentioned that using multiple conditional judgment is very difficult to maintain.
There are two main disadvantages of the strategy model:
Maintaining various policy classes will bring additional overhead to development. You may have experience in this regard: Generally speaking, the number of policy classes exceeds 5, which is more troublesome.
All policy classes must be exposed to the client (the caller) because it is up to the client to use, so the client should know what policies are there and understand the differences between various policies, otherwise the consequences are serious. For example, there is a strategy model for sorting algorithms that provide three algorithms: quick sorting, bubble sorting, and select sorting. Before using these algorithms, should the client understand the application of these three algorithms? For example, the client needs to use a container, which is implemented by linked lists and arrays. Does the client also need to understand the difference between linked lists and arrays? In this regard, it is contrary to the Dimitian law.
Applicable scenarios
When doing object-oriented design, you must be very familiar with the policy pattern, because it is essentially inheritance and polymorphism in object-oriented. After reading the general code of the policy pattern, I think that even if I have never heard of the policy pattern before, I must have used it during the development process, right? At least in the following two situations, you can consider using the strategy model.
The main logic of several classes is the same, and there are only slight differences in the algorithm and behavior of partial logic.
There are several similar behaviors, or algorithms, and the client needs to dynamically decide which one to use, so you can use the policy pattern to encapsulate these algorithms for client to call.
The strategy model is a simple and commonly used model. When we are developing, we often use it intentionally or unintentionally. Generally speaking, the strategy model will not be used alone, and it is more common to use it in mixed manner with template method mode, factory mode, etc.