Design Mode 14: Strategy Mode (Strategy)

In real life, often encountered in the presence of a variety of strategies to achieve a certain target to choose, for example, travelers can travel by plane, train, bike or start his own private cars, supermarkets may preclude the use of promotional discounts, delivery of goods send integration and other methods.

In software development often encountered a similar situation, when there are multiple algorithms or strategies to achieve a certain function, we can perform the function of different options, depending on environmental conditions or algorithm or strategy, such as data sorting strategies bubble sorting, selection sort, insertion sort, binary sorting.

If you use multiple conditional branch statement to achieve (that is hard-coded), not only conditional statements become very complex, and add, delete or replace algorithm to modify the source code, easy to maintain, contrary to the principle of opening and closing. If a pattern can be a good strategy to solve the problem.

The definition and characteristics of the strategy pattern

Defined strategy (Strategy) mode: This mode defines a set of algorithms and encapsulates each algorithm, so that they can replace each other, and the algorithm change does not affect customers using algorithms. Strategy pattern belong to the object behavior patterns, it encapsulated by algorithm, the algorithm of responsibility and the use of algorithms separated, and assigned to different objects to manage these algorithms.

The main advantage of the strategy pattern as follows.

  1. Multiple conditional statement is not easy to maintain, and use the strategy pattern to avoid the use of multiple conditional statements.
  2. Strategy pattern offers a range of family of algorithms available for reuse, the proper use of the algorithm can inherit the family of common code transferred to the parent class, so as to avoid duplication of code.
  3. Strategy Mode can provide different implementations of the same behavior, the customer can choose a different time or a different space requirements.
  4. Strategy mode provides perfect support for the principle of opening and closing, it can be without modifying the original code, flexible add new algorithms.
  5. Strategy pattern using the algorithm into the environment class, and the algorithm moves to class specific strategies to achieve a separation of the two.


The main drawback as follows.

  1. The client must understand the difference between all policies algorithms, in order to timely select the appropriate algorithm class.
  2. Strategy pattern cause a lot of strategy category.

Structure and implementation of the strategy pattern

Strategy pattern is to prepare a set of algorithms, and the set of packages to a series of algorithms which policy class as a subclass of abstract class policy. The focus of Strategy Mode is not how to implement the algorithm, but how to organize these algorithms, so that the program structure more flexible and has better maintainability and extensibility, and now we have to analyze the basic structure and implementation.

1. Structure Model

The main role of the strategy pattern as follows.

  1. Abstract Strategy (Strategy) category: defines a common interface to a variety of different algorithms in different ways this interface, the role of the environment using different interface calls this algorithm, commonly used interface or abstract class implements.
  2. Specific strategies (Concrete Strategy) category: abstract strategy to achieve the defined interfaces, provide specific algorithm.
  3. References hold a policy class, and ultimately to the client calls: Environment (Context) class.


The structure shown in Figure 1.
 

                                Graphic Organizer Strategy Mode
 

2. Mode of realization

Strategy pattern implementation code as follows:

package strategy;
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();
    }
}

Program results are as follows:  

具体策略A的策略方法被访问!
-----------------
具体策略B的策略方法被访问!

 

Application examples of the strategy pattern

[Example 1] Application Strategy Mode "hairy" in cooking.

Analysis: With regard to the practice of crabs there are many, we steamed crabs and crab braised two methods, for example, describes the application of the strategy pattern.

First, the abstract definition of a crab processing Strategy (CrabCooking), which contains an abstract of a method of cooking CookingMethod (); then, define the steamed crabs (SteamedCrabs) and braised crabs (BraisedCrabs) specific policy class, which implements the abstract method abstract class policy; FIG well as a result of the present procedure to be displayed, the policy class definition into a concrete subclass JLabel; Finally, the definition of a kitchen (kitchen) environment class, and having a set of selection policies cooking method; customer class policy by obtaining cooking class kitchen, cook and the results shown in FIG form, FIG 2 is a configuration diagram of FIG.
 

           Structure Figure cooking crabs policy

Code is as follows:

package strategy;
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();    //做菜   
    }
}

                              å¤§é¸è¹åèç »æ 

[Example 2] implemented the policy mode from Shaoguan travel to Wuyuan travel.

Analysis: from Shaoguan to Wuyuan tourism travel several ways: by train, by bus and by car, so the instance with the policy mode is more suitable, as shown in Figure 4 is its structure.
 

                Wuyuan tourism structure diagram
 

Strategy mode of application scenarios

Strategy mode is used in many places, such as  Java  container layout in the SE management is a typical example, Java SE in each container there for the user to select multiple layouts. In programming, the more commonly used strategy pattern in the following cases.

  1. A system needs to dynamically select one of several algorithms in the time, can be packaged into each algorithm class policy.
  2. A class defines a number of behavior and these behaviors in the form of a plurality of conditional statements in the operation of this class, each conditional branch may be moved into their respective policy class in place of the conditional statements.
  3. Each algorithm system completely independent of each other, and when the customer hide implementation details of the specific algorithm requirements.
  4. The system requires customers to use the algorithm should not know when the data in its operations, strategy pattern can be used to hide the algorithms associated with data structures .
  5. More than one class only difference in the performance of different behavior, you can use the Strategy pattern, behavior at runtime dynamically select specific to perform.

Expansion strategy mode

In a system using policy mode, when there is a strategy many clients manage all policies algorithm will become very complicated, if the policy factory pattern in the environment category to manage these policies classes will greatly reduce the complexity of the work the client , the structure shown in Figure 5.
 

             Graphic Organizer Strategy factory mode

 

Published 136 original articles · won praise 6 · views 1548

Guess you like

Origin blog.csdn.net/weixin_42073629/article/details/104437759