Brief description of strategy mode

I think it’s better to read the book repeatedly for design patterns. I recommend Head First and I also read this (https://pan.baidu.com/s/1x0aiZHEz_UMa_fKa8QNWbg ---- njh1)

Well, no thanks.

The standard definition is: the strategy model defines a family of algorithms, which are encapsulated separately so that they can be replaced with each other. This model makes the algorithm changes independent of the customers who use the algorithm

Simply put, there are several algorithms, which are used to decide which one to use

The class diagram is Jiangzi

code show as below:

package cn.bl.strategy;

/**
 * @Deacription 使用策略
 * @Author BarryLee
 * @Date 2019/9/22 16:21
 */
public class Main {
  public static void main(String[] args) {
    Context context = new Context();
    context.setStrategy(new ConcreteStrategyA());
    context.algorithm();

    context.setStrategy(new ConcreteStrategyB());
    context.algorithm();
  }
}
package cn.bl.strategy;

/**
 * 策略接口
 */
public interface Strategy {
  /**
   * 策略方法
   */
  void algorithm();
}
package cn.bl.strategy;

/**
 * @Deacription 环境类
 * @Author BarryLee
 * @Date 2019/9/22 16:21
 */
public class Context {

  // 策略是私有的
  private Strategy strategy;

  // 获取策略方法
  public Strategy getStrategy() {
    return strategy;
  }

  // 设置策略
  public void setStrategy(Strategy strategy) {
    this.strategy = strategy;
  }

  // 调用策略
  public void algorithm() {
    strategy.algorithm();
  }
}
package cn.bl.strategy;

/**
 * @Deacription 具体策略类A
 * @Author BarryLee
 * @Date 2019/9/22 16:21
 */
public class ConcreteStrategyA implements Strategy{
  @Override
  public void algorithm() {
    System.out.println("strategy A");
  }
}
package cn.bl.strategy;

/**
 * @Deacription 具体策略类B
 * @Author BarryLee
 * @Date 2019/9/22 16:22
 */
public class ConcreteStrategyB implements Strategy{
  @Override
  public void algorithm() {
    System.out.println("strategy B");
  }
}

 

Guess you like

Origin blog.csdn.net/qq_38238041/article/details/101162995