1.概述
策略模式是封装一组算法,在程序运行的过程中根据不同情况执行相应的算法。
2.UML结构图
image.png3.代码实现:
Strategy:策略接口
/**
* Created by zhouwen on 2019/7/13 17:16
*/
public interface Strategy {
void doing();
}
ConcreteStrategyA:具体策略角色
/**
* Created by zhouwen on 2019/7/13 17:16
*/
public class ConcreteStrategyA implements Strategy {
@Override
public void doing() {
Logger.getLogger("ConcreteStrategyA").info("A doing");
}
}
ConcreteStrategyB:具体策略角色
/**
* Created by zhouwen on 2019/7/13 17:17
*/
public class ConcreteStrategyB implements Strategy{
@Override
public void doing() {
Logger.getLogger("ConcreteStrategyB").info("B doing");
}
}
StrategyContext:封装角色,屏蔽上层对具体策略直接访问
/**
* Created by zhouwen on 2019/7/13 17:17
*/
public class StrategyContext {
private Strategy mStrategy;
public StrategyContext(Strategy mStrategy) {
this.mStrategy = mStrategy;
}
public void doing(){
mStrategy.doing();
}
}
StrategyClient:场景类
/**
* Created by zhouwen on 2019/7/13 17:31
*/
public class StrategyClient {
public void test(){
Strategy strategya = new ConcreteStrategyA();
Strategy strategyb = new ConcreteStrategyB();
StrategyContext strategyContext = new StrategyContext(strategya);
strategyContext.doing();
strategyContext = new StrategyContext(strategyb);
strategyContext.doing();
}
}
网友评论