Strategy mode "A mouse is a duck"

foreword

Hello everyone, I am god23bin, today we will introduce an important design pattern in the design pattern - strategy pattern .

The Strategy pattern is a common design pattern when it comes to having multiple variants of a certain behavior or algorithm. It allows the option to use different strategies at runtime without modifying existing code.

Now let's introduce it using the duck model that often appears in design patterns!

duck model

image-20230611120410421

The duck model is also easy to understand. It walks like a duck, swims like a duck, and makes a quacking sound. It is a duck model. It doesn’t matter whether it is a duck or not!

image-20230611120448020

strategy pattern

Define a series of algorithms, encapsulate them one by one, and make them interchangeable.

It mainly solves the complex and difficult-to-maintain problems caused by using if...else when there are many similar algorithms.

In the university cafeteria, there are many dishes, so we design a food Foodinterface to represent various dishes. This interface needs to have the ability to show what various foods are, so let’s design it as a showmethod.

public interface Food {
    void show();
}

Each food dish can be displayed, so we define a duck neck strategy class DuckNeckStrategyas a food dish strategy. This class implements Foodthe interface and overrides showthe method to show that this is a serious duck neck.

public class DuckNeckStrategy implements Food {
    @Override
    public void show() {
        System.out.println("嘎嘎嘎,我是正儿八经的鸭脖。");
    }
}

Next, we write a food strategy class that also implements Foodthe interface and Fooddeclares the food interface as an attribute of the class, which is called composition. Also write a constructor with Foodinterface parameters.

public class FoodStrategy implements Food {
    private Food food;

    public FoodStrategy(Food food) {
        this.food = food;
    }

    @Override
    public void show() {
        food.show();
    }
}

Now, our dining classmate comes on stage, write a Student class, and define a method to eat a serious duck neck.

public class Student {

    // 吃正儿八经的鸭脖
    public void eatDuckNeck() {
        Food duckNeck = new FoodStrategy(new DuckNeckStrategy());
        System.out.println("开吃!");
        duckNeck.show();
    }

}

Now let's run the program:

public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.eatDuckNeck();
    }
}

output:

开吃!
嘎嘎嘎,我是正儿八经的鸭脖。

Now we define a mouse head strategy class MouseHeadStrategy. As a dish strategy, it is necessary to implement Foodthe interface and rewrite showthe method to realize the display of the mouse head and duck neck dish.

public class MouseHeadStrategy implements Food {
    @Override
    public void show() {
        System.out.println("吱吱吱,我是长得像鼠头的鸭脖。");
    }
}

Next, add a meal to our classmates, define a method that can't help but eat duck necks, and pass a mouse head strategy as a parameter of the meal to the method.

public class Student {

    // 吃正儿八经的鸭脖
    public void eatDuckNeck() {
        Food duckNeck = new FoodStrategy(new DuckNeckStrategy());
        System.out.println("开吃!");
        duckNeck.show();
    }
	
    // 吱吱吱,吃鸭脖
    public void eatDuckNeck(MouseHeadStrategy mouseHeadStrategy) {
        Food duckNeck = new FoodStrategy(mouseHeadStrategy);
        System.out.println("开吃!");
        duckNeck.show();
    }

}

Now, pass a mouse head parameter to eatDuckNeckthe method , and let's continue to run the program.

public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        // 指鼠为鸭
        student.eatDuckNeck(new MouseHeadStrategy());
    }
}

output:

开吃!
吱吱吱,我是长得像鼠头的鸭脖。

Obviously, the program can still be executed, even if the mouse head is passed in, it can become a duck neck. This is the benefit that the strategy pattern brings to us. It allows us to choose different algorithms or strategies to achieve a certain function when the program is running without changing the existing code structure. Improve the flexibility of our code.

In this example, the strategy mode can decide what you eat through the strategy at runtime, and you can do whatever you want. If you want you to be a duck neck, you will be a duck neck, even if you are a mouse head.

image-20230611133502651

Summarize

The strategy pattern is written as follows:

  1. Define a common interface or abstract class to declare the methods that all policy classes must implement, such as showthe method .
  2. Define specific strategy classes, such as DuckNeckStrategyand MouseHeadStrategy, implement the methods in the interface, and each specific strategy class provides different algorithms or behavior implementations.
  3. Define a client class, such as here FoodStrategy, that holds a reference to a previously defined interface or abstract class, which is called a combination, implements the interface at the same time, implements a constructor, and uses different strategies to execute the rewritten interface method .
  4. Use this client class in the code, and pass in different strategies to the constructor to achieve different effects.

Source of inspiration for this article: www.bilibili.com/video/BV1jm…

last of the last

I hope everyone in front of the screen 靓仔靓女们will give a three-in-one! You gave a thumbs up lightly, that will add a bright and dazzling star to the world in my heart!

See you next time!

Guess you like

Origin juejin.im/post/7243240618787749946