Strategic model of design pattern series

Posted by DarkTempest on Wed, 20 Oct 2021 22:34:34 +0200

definition

The algorithm family is defined and encapsulated respectively so that they can be replaced with each other. This mode makes the change of the algorithm not affect the users using the algorithm.

The policy pattern emphasizes that multiple policies can be interchanged. These policies are different implementation classes of the same interface.

Pattern structure

The policy pattern involves three roles

  1. Abstract Strategy role
    Use interfaces or abstract classes to implement common behavior specifications that contain all policies. In particular, if the public behavior appears in the way of containing the method body rather than the interface method, only the abstract class can be used as the implementation of the role;
  2. Environment role (Context)
    Hold a Strategy reference for the client to call;
  3. Concrete strategy
    Implement the public behavior specification of abstract policy role definition;

The relationship between the three is shown in the figure below

Code practice

Suppose that a mall holds discount activities, which are divided into three strategies: full reduction, cash return and stand reduction. Different discount activities are implemented according to different situations. The three role codes of the policy mode are as follows

  • Environmental role

    /**
     * @description: Promotional activities - business logic
     * @Date: 2021/10/19 15:23
     */
    public class PromotionActivity {
        //Hold policy interface reference
        StrategyInterface strategyInterface;
        //Initialize policy interface through constructor
        public PromotionActivity(StrategyInterface strategyInterface){
            this.strategyInterface = strategyInterface;
        }
    
        //Business logic of promotional activities
        public void executePromption(){
            strategyInterface.doPromotion();
        }
    }
    
  • Abstract policy role

    //Defines how discounts are executed
    public interface StrategyInterface {
        void doPromotion();
    }
    
  • Three specific policy classes

    • Strategy I

      /**
       * @description: Cash back promotion -- a specific strategy implementation
       * @Date: 2021/10/19 15:22
       */
      public class FanxianPromotionStrategy implements StrategyInterface{
          @Override
          public void doPromotion() {
              System.out.println("Cash back promotion");
          }
      }
      
    • Strategy II

      /**
       * @description: Reduction strategy -- a specific strategy implementation
       * @Date: 2021/10/19 15:18
       */
      public class LijianPromitionStrategy implements StrategyInterface{
          @Override
          public void doPromotion() {
              System.out.println("Reduced promotion");
          }
      }
      
    • Strategy III

      /**
       * @description: Full reduction promotion -- a specific strategy implementation
       * @Date: 2021/10/19 15:21
       */
      public class ManjianPromitionStrategy implements StrategyInterface{
          @Override
          public void doPromotion() {
              System.out.println("Full reduction promotion");
          }
      }
      

    After the above code is written, the client can execute different discount policies as needed based on the environment object. For environmental roles, they only rely on abstraction and do not depend on concrete implementation. When a new policy appears, you only need to add a specific policy class without modifying other codes, which reflects the opening and closing principle. In this article, when new discount activities occur, just create a specific discount class that implements the StrategyInterface interface, and then call it in the client. No other code is needed.

    	/**
         * Create an environment role object and transfer the specific policy object to the environment role constructor according to business needs
         */
        static void baseTest(){
            //Use immediate discount
            PromotionActivity p618 = new PromotionActivity(new LijianPromitionStrategy());
            p618.executePromption();
    
            //Use cash back discount
            PromotionActivity p1111 = new PromotionActivity(new FanxianPromotionStrategy());
            p1111.executePromption();
        }
    

Source code analysis

The external comparator of java uses the policy mode. For details, see Two comparators of java

Applicable scenario

The policy pattern emphasizes the exchange of policies, so this feature should be used in its application scenarios.

  • When there are many ways to deal with the same type of problem, only when the specific behavior is different, the specific behavior is abstracted as a strategy;
  • When it is necessary to safely encapsulate multiple operations of the same type, the same type is abstracted as a policy;
  • When the same abstract class has multiple subclasses and you need to use if else or switch case to select specific subclasses. In this case, the judgment statement of if else can be removed in combination with the simple engineering mode. See for details Strategy mode + factory mode remove if else judgment

Topics: Java Design Pattern