Design Pattern-Strategic Design Pattern

1 Introduction

In real life, we often encounter situations where there are multiple strategies to choose from to achieve a certain goal. For example, travel can take an airplane, take a train, ride a bicycle or drive a private car, etc., and supermarket promotions can use discounts and deliver goods. , Send points and other methods.

Similar situations are often encountered in software development. When there are multiple algorithms or strategies to implement a certain function, we can choose different algorithms or strategies to complete the function according to different environments or conditions, such as bubbling in data sorting strategies. Sorting, selection sorting, insertion sorting, binary tree sorting, etc.

If you use multiple conditional transition statements to achieve (ie hard coding), not only the conditional statement becomes very complicated, but also the original code must be modified to add, delete or replace the algorithm, which is difficult to maintain and violates the principle of opening and closing. This problem can be solved well if the strategy model is adopted.

2. Definition and characteristics of the strategy model

Definition of Strategy mode: This mode defines a series of algorithms and encapsulates each algorithm so that they can be replaced with each other, and the change of the algorithm will not affect the customers who use the algorithm. The strategy mode belongs to the object behavior mode. It encapsulates the algorithm, separates the responsibility of using the algorithm and the realization of the algorithm, and delegates to different objects to manage these algorithms.

The main advantages of the strategy mode are as follows:

  1. Multiple conditional statements are not easy to maintain, and the use of strategy mode can avoid the use of multiple conditional statements, such as if...else statement, switch...case statement.
  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 to avoid duplication of code.
  3. The strategy mode can provide different realizations of the same behavior, and customers can choose different strategies according to different time or space requirements
  4. The strategy mode provides perfect support for the opening and closing principle, and new algorithms can be flexibly added without modifying the original code.
  5. The strategy mode puts the use of the algorithm in the environment class, and the realization of the algorithm is moved to the specific strategy class, realizing the separation of the two

The main disadvantages are as follows:

  1. The client must understand the difference between all strategy algorithms in order to select the appropriate algorithm class at the right time.
  2. The strategy mode creates a lot of strategy classes, which increases the difficulty of maintenance.

3. The structure and realization of the strategy model

The strategy mode is to prepare a set of algorithms and encapsulate this set of algorithms into a series of strategy classes as a subclass of an abstract strategy class. The focus of the strategy model is not how to implement the algorithms, but how to organize these algorithms so that the program structure is more flexible, with better maintainability and scalability. Now let's analyze its basic structure and implementation methods.

1. The structure of the model

The main roles of the strategy mode are as follows:

  1. Abstract strategy (Strategy) class: defines a public interface, and various algorithms implement this interface in different ways. Environmental actors use this interface to call different algorithms, generally implemented by interfaces or abstract classes.
  2. Concrete Strategy (Concrete Strategy) class: implements the interface defined by the abstract strategy and provides specific algorithm implementation.
  3. Environment (Context) class: holds a reference to a strategy class, which is finally called by the client.

Insert picture description here

2. Implementation of the pattern

public class StrategyPattern {
    
    
    public static void main(String[] args) {
    
    
        Context c = new Context();
        Strategy s = new ConcreteStrategyA();
        c.setStrategy(s);
        c.strategyMethod();
        System.out.println("-----------------");
        s = new ConcreteStrategyB();
        c.setStrategy(s);
        c.strategyMethod();
    }
}

//抽象策略类
interface Strategy {
    
    
    public void strategyMethod();    //策略方法
}

//具体策略类A
class ConcreteStrategyA implements Strategy {
    
    
    public void strategyMethod() {
    
    
        System.out.println("具体策略A的策略方法被访问!");
    }
}

//具体策略类B
class ConcreteStrategyB implements Strategy {
    
    
    public void strategyMethod() {
    
    
        System.out.println("具体策略B的策略方法被访问!");
    }
}

//环境类
class Context {
    
    
    private Strategy strategy;

    public Strategy getStrategy() {
    
    
        return strategy;
    }

    public void setStrategy(Strategy strategy) {
    
    
        this.strategy = strategy;
    }

    public void strategyMethod() {
    
    
        strategy.strategyMethod();
    }
}

The strategy method of specific strategy A is accessed!
-----------------
The strategy method of specific strategy B is accessed!

4. Application examples of strategy mode

[Example 1] The application of strategy mode in "hairy crab" cooking.

Analysis: There are many methods for hairy crabs. We take two methods, steamed hairy crabs and braised hairy crabs, as examples to introduce the application of the strategy model.

First, define an abstract strategy class (CrabCooking) for processing hairy crabs, which contains an abstract cooking method CookingMethod(); then, define specific strategy classes for steamed crabs (SteamedCrabs) and braised crabs (BraisedCrabs), which implement abstraction The abstract method in the strategy class; because this program wants to display the finished result graph, the specific strategy class is defined as a subclass of JLabel; finally, a kitchen (Kitchen) environment class is defined, which has settings and selection of cooking strategies Method: The customer class obtains the cooking strategy through the kitchen class, and displays the cooking result graph in the form. Figure 2 shows its structure.

Insert picture description here

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CrabCookingStrategy implements ItemListener {
    
    
        private JFrame f;
        private JRadioButton qz, hs;
        private JPanel CenterJP, SouthJP;
        private Kitchen cf;    //厨房
        private CrabCooking qzx, hsx;    //大闸蟹加工者  
        CrabCookingStrategy() {
    
    
            f = new JFrame("策略模式在大闸蟹做菜中的应用");
            f.setBounds(100, 100, 500, 400);
            f.setVisible(true);
            f.setResizable(false);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            SouthJP = new JPanel();
            CenterJP = new JPanel();
            f.add("South", SouthJP);
            f.add("Center", CenterJP);
            qz = new JRadioButton("清蒸大闸蟹");
            hs = new JRadioButton("红烧大闸蟹");
            qz.addItemListener(this);
            hs.addItemListener(this);
            ButtonGroup group = new ButtonGroup();
            group.add(qz);
            group.add(hs);
            SouthJP.add(qz);
            SouthJP.add(hs);
            //---------------------------------
            cf = new Kitchen();    //厨房
            qzx = new SteamedCrabs();    //清蒸大闸蟹类
            hsx = new BraisedCrabs();    //红烧大闸蟹类
        }
        public void itemStateChanged(ItemEvent e) {
    
    
            JRadioButton jc = (JRadioButton) e.getSource();
            if (jc == qz) {
    
    
                cf.setStrategy(qzx);
                cf.CookingMethod(); //清蒸
            } else if (jc == hs) {
    
    
                cf.setStrategy(hsx);
                cf.CookingMethod(); //红烧
            }
            CenterJP.removeAll();
            CenterJP.repaint();
            CenterJP.add((Component) cf.getStrategy());
            f.setVisible(true);
        }
        public static void main(String[] args) {
    
    
            new CrabCookingStrategy();
        }
    }
    //抽象策略类:大闸蟹加工类
    interface CrabCooking {
    
    
        public void CookingMethod();    //做菜方法
    }
    //具体策略类:清蒸大闸蟹
    class SteamedCrabs extends JLabel implements CrabCooking {
    
    
        private static final long serialVersionUID = 1L;
        public void CookingMethod() {
    
    
            this.setIcon(new ImageIcon("src/strategy/SteamedCrabs.jpg"));
            this.setHorizontalAlignment(CENTER);
        }
    }
    //具体策略类:红烧大闸蟹
    class BraisedCrabs extends JLabel implements CrabCooking {
    
    
        private static final long serialVersionUID = 1L;
        public void CookingMethod() {
    
    
            this.setIcon(new ImageIcon("src/strategy/BraisedCrabs.jpg"));
            this.setHorizontalAlignment(CENTER);
        }
    }
    //环境类:厨房
    class Kitchen {
    
    
        private CrabCooking strategy;    //抽象策略
        public void setStrategy(CrabCooking strategy) {
    
    
            this.strategy = strategy;
        }
        public CrabCooking getStrategy() {
    
    
            return strategy;
        }
        public void CookingMethod() {
    
    
            strategy.CookingMethod();    //做菜  
        }
    }

Insert picture description here

[Example 2] The strategy model is used to realize the travel mode from Shaoguan to Wuyuan.

Analysis: There are several ways to travel from Shaoguan to Wuyuan: train, car and self-driving. Therefore, the strategy mode is more suitable for this example. Figure 4 shows its structure.

Insert picture description here

5. Application scenarios of strategy mode

Strategy mode is used in many places. For example, container layout management in Java SE is a typical example. Each container in Java SE has multiple layouts for users to choose from. In program design, strategy patterns are usually used in the following situations.

  1. When a system needs to dynamically select one of several algorithms, each algorithm can be encapsulated into a strategy class.
  2. A class defines multiple behaviors, and these behaviors appear in the form of multiple conditional statements in the operation of this class. Each conditional branch can be moved into their respective strategy classes to replace these conditional statements.
  3. When the algorithms in the system are completely independent of each other, and the implementation details of specific algorithms are required to be hidden from customers.
  4. When the system requires that the customer who uses the algorithm should not know the data of its operation, the strategy mode can be used to hide the data structure related to the algorithm.
  5. Multiple classes only differ in their performance behaviors. You can use the strategy mode to dynamically select specific behaviors to be executed at runtime.

6. Expansion of Strategy Mode

In a system using the strategy mode, when there are many strategies, the client management of all strategy algorithms will become very complicated. If the strategy factory mode is used in the environment class to manage these strategy classes, the work complexity of the client will be greatly reduced. , Its structure diagram is shown in Figure 5.
Insert picture description here

Guess you like

Origin blog.csdn.net/saienenen/article/details/112671093