面向对象设计模式-策略模式
参考书籍:大话设计模式-程杰 著
一,UML图
二,定义:
策略模式是一种定义一系列算法的方法,这些算法都是完成相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合度(DPE)
三,代码示例:
// 算法接口
interface Strategy{
// 算法方法
public void algorithmInterface();
}
// 具体算法类 A
class StrategyA implement Strategy{
// 算法A的实现
public void algorithmInterface(){
System.out.println("算法A实现");
}
}
// 具体算法类 B
class StrategyB implement Strategy{
// 算法B的实现
public void algorithmInterface(){
System.out.println("算法B实现");
}
}
// 具体算法类 C
class StrategyC implement Strategy{
// 算法C的实现
public void algorithmInterface(){
System.out.println("算法C实现");
}
}
// 上下文
class Context {
private Strategy strategy;
public Contenxt(Strategy strategy){
this.strategy = strategy;
}
// 上下文接口
public void ContextInterface(){
strategy.algorithmInterface();
}
}
调用代码
...
public static void main(String[] args){
Context context = null;
context = new Context(new StrategyA());
context.ContextInterface();
context = new Context(new StrategyB());
context.ContextInterface();
context = new Context(new StrategyC());
context.ContextInterface();}
...