策略模式-实践
策略模式
1. 定义一个策略接口
public interface IFileStrategy {
// 获取文件类型
FileTypeResolveEnum gainFileType();
// 文件处理的方法
void resolve(Object objectParam);
}
enum FileTypeResolveEnum {
FILE_A_RESOLVE,
FILE_B_RESOLVE;
}
策略A的实现方式
/**
* 文件A的处理策略
*/
@Component
@Slf4j
public class AFileResolve implements IFileStrategy {
@Override
public FileTypeResolveEnum gainFileType() {
return FileTypeResolveEnum.FILE_A_RESOLVE;
}
@Override
public void resolve(Object objectParam) {
log.info("A类型解析文件的参数" + objectParam);
}
}
策略B的实现
/**
* 文件B的处理策略
*/
@Slf4j
@Component
public class BFileResolve implements IFileStrategy {
@Override
public FileTypeResolveEnum gainFileType() {
return FileTypeResolveEnum.FILE_B_RESOLVE;
}
@Override
public void resolve(Object objectParam) {
log.info("B文件类型解析参数" + objectParam);
}
}
策略的使用
@Component
public class StrategyService implements ApplicationContextAware {
private Map<FileTypeResolveEnum, IFileStrategy> map = new ConcurrentHashMap<>();
public void resolveFile(FileTypeResolveEnum fileTypeResolveEnum, Object objectParam) {
IFileStrategy fileStrategy = map.get(fileTypeResolveEnum);
if (fileStrategy != null) {
fileStrategy.resolve(objectParam);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Map<String, IFileStrategy> beansOfType = applicationContext.getBeansOfType(IFileStrategy.class);
Collection<IFileStrategy> values = beansOfType.values();
values.stream().forEach(fileStrategy -> map.put(fileStrategy.gainFileType(), fileStrategy));
}
}