策略模式:定义一系列算法,然后将每一个算法封装起来,并将它们可以互相替换。也就是将一系列算法封装到一系列策略类里面。策略模式是一种对象行为型模式。策略模式符合“开闭原则“
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.
不用策略模式的情况:
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();
相同点:
不同点:
对状态模式不是很熟悉,可以参考我以前写的一篇博客