一、模式定义

策略模式:定义一系列算法,然后将每一个算法封装起来,并将它们可以互相替换。也就是将一系列算法封装到一系列策略类里面。策略模式是一种对象行为型模式。策略模式符合“开闭原则“

Strategy Pattern: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

二、模式角色

  • Context :环境类
  • Strategy:抽象策略类
  • ConcreteStrategy:具体策略类

三、简单实例

不用策略模式的情况:

public class Context
{
……
public void method(String type)
{
......
if(type == "strategyA")
{
//算法A
}
else if(type == "strategyB")
{
//算法B
}
else if(type == "strategyC")
{
//算法C
}
......
}
……
}

抽象策略类:

public abstract class AbstractStrategy
{
public abstract void method();
}

具体策略类:

public class ConcreteStrategyA extends AbstractStrategy
{
public void method()
{
//算法A
}
}

环境类:

public class Context
{
private AbstractStrategy strategy;
public void setStrategy(AbstractStrategy strategy)
{
this.strategy= strategy;
}
public void method()
{
strategy.method();
}
}

客户端调用:

Context context = new Context();
AbstractStrategy strategy;
strategy = new ConcreteStrategyA();
context.setStrategy(strategy);
context.method();

四、策略模式和状态模式对比

相同点:

  • 策略模式和状态模式都是属于行为型设计模式,也同样是对象行为型设计模式,非类行为型设计模式。
  • 策略模式和状态模式有点类似,都符合”闭合原则“
  • 两个设计模式都可以用于减少代码大量的if…else

不同点:

  • 具体使用策略模式还是状态模式,可以通过环境类的状态而定,有很多状态的话,就使用状态模式。
  • 使用策略模式时,环境类需要选择一个确定的策略类,也就是客户端调时需要关心具体状态,根据需要调用;而状态模式是不需要的,在状态模式里,环境类是要放在一个具体状态中的,也就是根据环境类的状态改变进行调用状态类的算法

对状态模式不是很熟悉,可以参考我以前写的一篇博客