一、概念
策略模式(Strategy Pattern):定义一族算法类,将每个算法分别封装起来,让它们可以互相替换。
与工厂模式区别:策略模式和工厂模式结构很像。工厂模式是解耦对象的创建和使用,策略模式解耦的是策略的定义、创建、使用这三部分。
二、实现
这里以三国时期诸葛亮给刘备三个锦囊的故事为例子,锦囊相当于解决策略。
1、策略接口
public interface Strategy {
void openSecretStrategy();
}
2、三个秘密锦囊
public class FirstSecretStrategy implements Strategy{
@Override
public void openSecretStrategy() {
System.out.println("打开第一个锦囊,见乔国老,并把刘备娶亲的事情搞得东吴人尽皆知");
}
}
public class SecondSecretStrategy implements Strategy{
@Override
public void openSecretStrategy() {
System.out.println("打开第二个锦囊,用谎言(曹操打荆州)骗泡在温柔乡里的刘备回去");
}
}
public class ThirdSecretStrategy implements Strategy{
@Override
public void openSecretStrategy() {
System.out.println("打开第三个锦囊,让孙夫人摆平东吴的追兵,她是孙权妹妹,东吴将领惧她三分");
}
}
3、策略工厂
public class SecretStrategyFactory {
private static final HashMap<String, Strategy> strategies = new HashMap<>();
static {
strategies.put("第一个紧急关头", new FirstSecretStrategy());
strategies.put("第二个紧急关头", new SecondSecretStrategy());
strategies.put("第三个紧急关头", new ThirdSecretStrategy());
}
public static Strategy getSecretStrategy(String type) {
if (type == null || type.isEmpty()) {
throw new IllegalArgumentException("type should not be empty.");
}
return strategies.get(type);
}
}
4、测试类:
public class Client {
public static void main(String[] args) {
Strategy firstStrategy = SecretStrategyFactory.getSecretStrategy("第一个紧急关头");
firstStrategy.openSecretStrategy();
System.out.println("---------------");
Strategy secondStrategy = SecretStrategyFactory.getSecretStrategy("第二个紧急关头");
secondStrategy.openSecretStrategy();
System.out.println("---------------");
Strategy thirdStrategy = SecretStrategyFactory.getSecretStrategy("第三个紧急关头");
thirdStrategy.openSecretStrategy();
}
}
5、运行结果: