# 策略模式
# 简介
行为型模式,根据不同的情况选择不同的算法策略。Context:上下文角色,屏蔽高层模块对策略、算法的直接访问。简单的策略算法,可以采用枚举策略写法。
# 示例
public interface IStrategy {
void doSomeThing();
}
public class StrategyA implements IStrategy{
@Override
public void doSomeThing() {
System.out.println("Algorithm A do some thing!");
}
}
public class StrategyB implements IStrategy{
@Override
public void doSomeThing() {
System.out.println("Algorithm B do some thing!");
}
}
public class StrategyC implements IStrategy{
@Override
public void doSomeThing() {
System.out.println("Algorithm C do some thing!");
}
}
public class Context {
private IStrategy strategy;
public Context(IStrategy strategy){
this.strategy = strategy;
}
public void doSomeThing(){
strategy.doSomeThing();
}
}
# 调用
@Test
public void tt(){
Context context = new Context(new StrategyA());
context.doSomeThing();
context = new Context(new StrategyB());
context.doSomeThing();
context = new Context(new StrategyC());
context.doSomeThing();
}
# 枚举策略
public enum Strategy {
A{
@Override
public void doSomeThing(){
System.out.println("Algorithm A do some thing!");
}
},
B{
@Override
public void doSomeThing(){
System.out.println("Algorithm B do some thing!");
}
},
C{
@Override
public void doSomeThing(){
System.out.println("Algorithm C do some thing!");
}
};
public abstract void doSomeThing();
}
# 调用
@Test
public void tt2(){
Strategy.A.doSomeThing();
Strategy.B.doSomeThing();
Strategy.C.doSomeThing();
}