策略模式
时间:2017-12-02 23:25:29
参考:
- 设计模式之禅 [秦小波]
¶
策略模式(Strategy Pattern)¶
把多个策略抽象出来,由具体的调用者决定在调用的时候使用什么策略。
Deifine a family of algorithms, encapsulate each one, and make them interchangeable.
定义一组算法,封装每一个算法,是他们可以互换。
类图¶
简单策略代码¶
//策略接口
class interface Strategy {
public void exec();
}
//策略A
class StrategyA implements Strategy {
public void exec() {
System.out.println("A");
}
}
//策略B
class StrategyB implements Strategy {
public void exec() {
System.out.println("A");
}
}
//容器类,持有策略
class Context {
private Strategy strategy;
public Context(Strategy startegy) {
this.strategy = strategy;
}
public void run() {
strategy.exec();
}
}
// 客户端调用
class Client {
public static void main(String[] args) {
new Context(new StrategyA().exec());
new Context(new StrategyB().exec());
}
}