在说策略模式之前,我们首先要说下Unix/Linux的接口设计有一句通用“提供机制而不是策略”的格言。 什么是策略,策略有点像战术是具体的东西。而机制像战略是目的。
通俗来说机制是做什么,策略是怎么做。我们知道人要吃饭,但中国人和美国人吃饭不一样。我们用策略模式实现如下:
public class Strategy {
// 抽象策略
interface EatStrategy {
void eatFood();
}
static class ChinaEatStrategy implements EatStrategy {
public void eatFood() {
System.out.println("用筷子吃中餐");
}
}
static class AmericanEatStrategy implements EatStrategy {
public void eatFood() {
System.out.println("用刀叉吃西餐");
}
}
//环境类,提供机制
static class EatContext {
private EatStrategy travelStrategy;
EatContext(String type) {
switch (type) {
case "china"://这里可以提供单例
this.travelStrategy = new ChinaEatStrategy();
break;
case "american":
this.travelStrategy = new AmericanEatStrategy();
break;
}
}
public void eat() {
travelStrategy.eatFood();
}
}
public static void main(String[] args) {
EatContext context = new EatContext("china");
context.eat();
context = new EatContext("american");
context.eat();
}
}
输出:
用筷子吃中餐
用刀叉吃西餐
我想说提供机制而不提供策略的下句:策略应该是可选的。
觉得容易理解的话面向对象的23种设计模式点这里