Design pattern---Strategy pattern

1 Definition

The Strategy Pattern is to bring together a group of algorithms with the same purpose and different implementation methods, so that they can be replaced with each other, and the changes of the algorithm will not affect the customers who use the algorithm. The strategy pattern belongs to the object behavior pattern. It encapsulates the algorithm, separates the responsibility of using the algorithm from the implementation of the algorithm, and delegates the management of these algorithms to different objects.

2 Advantages 

1. Multiple conditional statements are not easy to maintain, and using the strategy pattern can avoid the use of multiple conditional statements, such as if...else statements, switch...case statements.

2. The strategy pattern provides a series of reusable algorithm families. Proper use of inheritance can transfer the common code of the algorithm family to the parent class, thereby avoiding duplication of code.

3. The strategy mode can provide different implementations of the same behavior, and customers can choose different ones according to different time or space requirements.

4. The strategy mode provides perfect support for the open-closed principle, and can flexibly add new algorithms without modifying the original code.

5. The strategy mode puts the use of the algorithm into the environment class, and moves the implementation of the algorithm into the concrete strategy class, realizing the separation of the two.

6. The strategy pattern combined with the factory pattern can reduce the coupling between the client class and the algorithm abstraction.

3 examples to explain

Depending on the weather, there can be different strategies for going to work each day. It's sunny, bike to work, rainy, subway to work, windy, drive to work, snow, walk to work. The client chooses different work strategies according to the weather conditions.

4 UML class diagram

5 Sample code

5.1 WayToWorkStrategy interface

public interface WayToWorkStrategy {

    /**
     * 如何去上班
     * @return 上班方式
     */
    String chooseWayToWork();
}

 5.2 BicycleWay

public class BicycleWay implements WayToWorkStrategy{

    @Override
    public String chooseWayToWork() {
       return "骑自行车去上班";
    }
}

5.3 CarWay car

public class CarWay implements WayToWorkStrategy{

    @Override
    public String chooseWayToWork() {
        return "开车去上班";
    }
}

5.4 SubwayWay

public class SubwayWay implements WayToWorkStrategy{

    @Override
    public String chooseWayToWork() {
       return "坐地铁去上班";
    }
}

5.5 WalkWay

public class WalkWay implements WayToWorkStrategy{

    @Override
    public String chooseWayToWork() {
        return "走路去上班";
    }
}

5.6 References to ContextStrategy Strategy Objects

public class ContextStrategy {
    private String climate;
    WayToWorkStrategy wayToWorkStrategy;
    public ContextStrategy(String climate){
        this.climate = climate;
        this.wayToWorkStrategy = chooseContextStrategy();
    }

    private WayToWorkStrategy chooseContextStrategy(){
        //简单工厂模式
        switch (climate) {
            case "sun":
                return new BicycleWay();
            case "rain":
                return new SubwayWay();
            case "wind":
                return new CarWay();
            case "snow":
                return new WalkWay();
            default:
               return null;
        }
    }

    /**
     * 获取上班策略
     * @return 上班策略
     */
    public String showWayToWork(){
        if (wayToWorkStrategy == null){
            return "天气不符合要求,无法上班,好开心";
        }
        return wayToWorkStrategy.chooseWayToWork();
    }
}

5.7 MainClass main function

public class MainClass {
    public static void main(String[] args) {
        boolean flag = true;
        while (flag) {
            //模拟天气参数
            Scanner sc = new Scanner(System.in);
            String climate = sc.nextLine();
            if (climate.equals("exit")) {
                flag = false;
            } else {
                ContextStrategy strategy = new ContextStrategy(climate);
                System.out.println(strategy.showWayToWork());
            }
        }
    }
}

5.8 Running Results

6 Quotes

1. "Dahua Design Patterns"

2. Detailed Explanation of Strategy Pattern (Strategy Design Pattern) 

7 Source code

https://github.com/airhonor/design-pattern-learning/tree/main/src/com/hz/design/pattern/strategy

Guess you like

Origin blog.csdn.net/honor_zhang/article/details/120078247