目录
策略模式最常见的应用场景是:利用它来避免冗长的 if-else 或 switch 分支判断。
策略模式定义:定义一族算法类,将每个算法分别封装起来,让它们可以互相替换。策略模式可以使算法的变化独立于使用它们的客户端(这里的客户端代指使用算法的代码)。
一、策略类的定义
策略类的定义比较简单,包含一个策略接口和一组实现这个接口的策略类。因为所有的策略类都实现相同的接口,所以,客户端代码基于接口而非实现编程,可以灵活地替换不同的策略。
public interface Strategy {
void algorithmInterface();
}
public class ConcreteStrategyA implements Strategy {
@Override
public void algorithmInterface() {
//具体的算法...
}
}
public class ConcreteStrategyB implements Strategy {
@Override
public void algorithmInterface() {
//具体的算法...
}
}
二、策略的创建
使用工厂方法模式创建
因为策略模式会包含一组策略,在使用它们的时候,一般会通过类型(type)来判断创建哪个策略来使用。为了封装创建逻辑,我们需要对客户端代码屏蔽创建细节。我们可以把根据 type 创建策略的逻辑抽离出来,放到工厂类中。
public class StrategyFactory {
private static final Map<String, Strategy> strategies = new HashMap<>();
static {
strategies.put("A", new ConcreteStrategyA());
strategies.put("B", new ConcreteStrategyB());
}
public static Strategy getStrategy(String type) {
if (type == null || type.isEmpty()) {
throw new IllegalArgumentException("type should not be empty.");
}
return strategies.get(type);
}
}
一般来讲,如果策略类是无状态的,不包含成员变量,只是纯粹的算法实现,这样的策略对象是可以被共享使用的,不需要在每次调用 getStrategy() 的时候,都创建一个新的策略对象。针对这种情况,我们可以使用上面这种工厂类的实现方式,事先创建好每个策略对象,缓存到工厂类中,用的时候直接返回。
相反,如果策略类是有状态的,根据业务场景的需要,我们希望每次从工厂方法中,获得的都是新创建的策略对象,而不是缓存好可共享的策略对象,那我们就需要按照如下方式来实现策略工厂类。
public class StrategyFactory {
public static Strategy getStrategy(String type) {
if (type == null || type.isEmpty()) {
throw new IllegalArgumentException("type should not be empty.");
}
if (type.equals("A")) {
return new ConcreteStrategyA();
} else if (type.equals("B")) {
return new ConcreteStrategyB();
}
return null;
}
}
对于 Java 语言来说,我们可以通过反射来避免对策略工厂类的修改。
具体是这么做的:我们通过一个配置文件或者自定义的 annotation 来标注都有哪些策略类;策略工厂类读取配置文件或者搜索被 annotation 标注的策略类,然后通过反射动态地加载这些策略类、创建策略对象;当我们新添加一个策略的时候,只需要将这个新添加的策略类添加到配置文件或者用 annotation 标注即可。
// 策略类配置文件地址
private static final String CONSUME_PROCESSOR_CONFIG_FILE_PATH = "META-INF/oc2/oc2-message-processor.properties";
// 加载配置文件中的所有策略类
private void initConsumeProcessorMapping() throws IOException {
Map<String, Processable> processors = buildBeanMappingInfo(CONSUME_PROCESSOR_CONFIG_FILE_PATH, Processable.class);
ConsumeProcessorMapping.setProcessors(processors);
}
// 构建Bean的映射关系
private static <T> Map<String, T> buildBeanMappingInfo(String configPath, Class<T> clazz) throws IOException {
// 1.获取配置参数
Properties configProperties = getConfigProperties(configPath);
if(MapUtils.isEmpty(configProperties)){
return null;
}
Map<String, T> mappingInfo = Maps.newHashMapWithExpectedSize(configProperties.size());
for(String mappingKey : configProperties.stringPropertyNames()){
// 2. 根据配置参数获取对应的Bean
String beanName = configProperties.getProperty(mappingKey);
// 通过ApplicationContext的getBean方法动态的获取Spring容器中已初始化的bean。
T mappingBean = SpringContextUtils.getApplicationContext().getBean(beanName, clazz);
if(mappingBean == null){
throw new ValidationException("bean: " + beanName + " not exist");
}
// 3. 设置映射关系
mappingInfo.put(mappingKey, mappingBean);
}
return mappingInfo;
}
private static Properties getConfigProperties(String configPath) throws IOException {
return PropertiesLoaderUtils.loadAllProperties(configPath, DmsProcessorInitializer.class.getClassLoader());
}
*getBean()的使用方法
三、策略的使用
在程序运行期间,根据配置、用户输入、计算结果等这些不确定因素,动态决定使用哪种策略。
可以用 Map 来缓存策略,根据 type 直接从 Map 中获取对应的策略,从而避免 if-else 分支判断逻辑。活着其他,本质为“查表法”的方式,根据 type 查表(代码中的 strategies 就是表)替代根据 type 分支判断。
实现一个支持给不同大小文件排序的小程序