This is the second day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Hello, I’m Bella Sauce

Today we are going to talk about strategy patterns, mainly the following aspects: definitions, real-life examples, core components, UML diagrams, code implementation, application scenarios, etc.

define

What is the strategic pattern?

To quote from GoF’s book design Patterns: A Foundation for Reusable Object-oriented Software:

Define a set of algorithms, encapsulate them one by one, and make them interchangeable. This pattern allows the algorithm to change independently of the customers who use it.

What does that mean? That is, there are N algorithms, they want to achieve the same purpose, so the algorithms are interchangeable, each client independently choose which algorithm to use, different clients can choose different algorithms.

Examples from life

In fact, there are many examples of using strategic patterns in our daily life.

For example, one of the things we do on most weekdays is to use some form of transportation to get from home to work. What kind of transportation do you use? According to the distance from home to work, different students will choose different modes of transportation, such as taking the subway, driving, cycling, walking and so on.

Regardless of the mode of transportation, our purpose is the same — to get from home to work. The modes of transportation are independent and interchangeable. Each student will choose different modes of transportation according to their actual situation. Isn’t this a classic example of a strategic pattern?

The core of

The strategy pattern is mainly composed of four parts:

  1. Strategy Indicates the policy interface. The interface defines a method that each specific policy class implements.
  2. ConcreteStrategy specifies the ConcreteStrategy. There are several ConcreteStrategy implementations, all of which implement the methods defined in the Strategy policy interface.
  3. Context Context. The Context defines the policy class and defines a method that, when executed, executes the methods in each specific policy.
  4. Client Indicates the Client. Client The Client creates the Context and specifies the specific policy class, and then executes the methods defined in the Strategy policy interface.

Take the example above:

  1. Strategy The Strategy interface defines a method to choose the mode of transportation from home to business.
  2. ConcreteStrategy Concrete strategies, such as subway strategy, self-driving strategy, cycling strategy and so on, all realize the method of “choosing the transportation mode from home to company”, but the method body of each specific strategy is different.
  3. The Strategy policy class is defined in the Context of Context, and there is also a method in the Context of Context that executes the methods defined in the Strategy policy interface.
  4. Client Creates a Context and specifies which specific policy to use, such as a cycling policy, and then calls the methods defined in the Context to execute the methods in the policy.

UML diagrams

For the example in the above article, the UML diagram of the policy pattern is as follows:

If you are confused about UML class diagrams, you can read this article: Understanding UML Class Diagrams

Code implementation

Let’s see how to implement the above example in code, so cool ~

First define a Strategy policy interface.

package com.bella.design.patterns.strategy; /** * Strategy class ** @author Bella paste * @date 2021/08/08 */ Public interface Strategy {/** * select ** from home ** @param home * @param company * @return transportation */ String selectTransportation(String home, String company); }Copy the code

Secondly, three specific strategies are defined, namely SubwayStrategy, CarStrategy and BikeStrategy. SubwayStrategy SubwayStrategy.

package com.bella.design.patterns.strategy; import java.text.MessageFormat; /** * SubwayStrategy implements Strategy ** @author Bella * @date 2021/08/08 */ public class SubwayStrategy implements Strategy {/** * Select ** * SubwayStrategy implements Strategy * * @param home * @param company * @return */ public String selectTransportation(String home, String company) {system.out.println (messageformat.format (" home is at -{0}, company is at -{1}, it is recommended that you take the train!" , home, company)); return "Subway"; }}Copy the code

CarStrategy Self-driving strategy.

package com.bella.design.patterns.strategy; import java.text.MessageFormat; /** * implements Strategy ** @author Bella * @date 2021/08/08 */ public class CarStrategy implements Strategy {/** * Implements Strategy ** * @param home * @param company * @return */ public String selectTransportation(String home, String company) {system.out.println (messageformat.format (" home is at -{0}, company is at -{1}, seat belt is on, we are ready to go!" , home, company)); return "Car"; }}Copy the code

BikeStrategy.

package com.bella.design.patterns.strategy; import java.text.MessageFormat; /** ** @author Bella Bella * @date 2021/08/08 */ public class BikeStrategy implements Strategy {/** * Select transportation from home to company * * @param home * @param company * @return */ public String selectTransportation(String home, String company) {system.out.println (messageformat.format (" home in -{0}, company in -{1}, green travel, contribute to environmental protection!" , home, company)); return "Bike"; }}Copy the code

And then we define the Context.

package com.bella.design.patterns.strategy; /** * @author Bella pickle * @date 2021/08/08 */ public class Context {/** * private Strategy Strategy; public Context(Strategy strategy) { this.strategy = strategy; } @param home * @param home * @param home * @param home * @param home * @return */ public String selectTransToCompany(String home, String company) { return strategy.selectTransportation(home, company); }}Copy the code

Finally, a test class to test the effect ~

package com.bella.design.patterns.strategy; Public class StrategyTest {public static void main(String[]) args) { Context strategyContext = new Context(new SubwayStrategy()); String trans = strategyContext. SelectTransToCompany (" the beijing-hangzhou grand canal ", "the future of science and technology city"); System.out.println(trans); strategyContext = new Context(new CarStrategy()); Trans = strategyContext. SelectTransToCompany (" old yuhang ", "the future of science and technology city"); System.out.println(trans); strategyContext = new Context(new BikeStrategy()); Trans = strategyContext. SelectTransToCompany (" the future of science and technology city ", "the future of science and technology city"); System.out.println(trans); }}Copy the code

Run StrategyTest, and the results are as follows:

No, that’s exactly what we want!

Applicable scenario

From the above explanation, I believe you have mastered the use of strategic patterns, but when should we use strategic patterns?

  1. When a behavior executes different method bodies for different conditions. It’s actually the if else we always see. For the if else statement in your project, consider whether you can define different concrete policy classes and move the else statement into each ConcreteStrategy.
  2. When many similar classes differ only in their behavior. Are these similar classes like different ConcreteStrategies? A wave of refactoring of similar classes using the strategy pattern will make the code structure much cleaner and much more readable!
  3. When there are several different implementations of an algorithm, and new implementations may be added later. With strategy mode, you can add an algorithm implementation without modifying the existing algorithm implementation, greatly reducing the risk of introducing new strategies.

Well, that’s all for today’s article. The code in this article can be found at github.com/lilinru/des… Download it here and see you next time