Notes
Search…
Strategy

概念

策略模式:Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. 定义一族算法类,将每个算法分别封装起来,让它们可以互相替换。策略模式可以使算法的变化独立于使用它们的客户端。
策略模式用于解耦策略的定义、创建、使用三部分。
常见的应用场景是避免冗长的 if-else 或 switch 分支判断。也能像模板方法一样,提供框架扩展点。

示例

定义

1
public interface Strategy {
2
void algorithmInterface();
3
}
4
5
public class ConcreteStrategyA implements Strategy {
6
@Override
7
public void algorithmInterface() {
8
//具体的算法...
9
}
10
}
11
12
public class ConcreteStrategyB implements Strategy {
13
...
14
}
Copied!

创建

1
public class StrategyFactory {
2
private static final Map<String, Strategy> strategies = new HashMap<>();
3
4
static {
5
strategies.put("A", new ConcreteStrategyA());
6
strategies.put("B", new ConcreteStrategyB());
7
}
8
9
public static Strategy getStrategy(String type) {
10
if (type == null || type.isEmpty()) {
11
throw new IllegalArgumentException("type should not be empty.");
12
}
13
return strategies.get(type);
14
}
15
}
Copied!
对于无状态的策略类,可以使用上面的方式,事先创建好策略实例。如果是有状态的,则需要每次新创建策略实例。

使用

1
// 策略接口:EvictionStrategy
2
// 策略类:LruEvictionStrategy、FifoEvictionStrategy、LfuEvictionStrategy...
3
// 策略工厂:EvictionStrategyFactory
4
5
// 运行时动态确定,根据配置文件的配置决定使用哪种策略
6
public class Application {
7
public static void main(String[] args) throws Exception {
8
EvictionStrategy evictionStrategy = null;
9
Properties props = new Properties();
10
props.load(new FileInputStream("./config.properties"));
11
String type = props.getProperty("eviction_type");
12
evictionStrategy = EvictionStrategyFactory.getEvictionStrategy(type);
13
UserCache userCache = new UserCache(evictionStrategy);
14
//...
15
}
16
}
Copied!
Last modified 1yr ago