我使用lambda表达式+函数来实现策略模式,我是否正确使用它?
public void deploy(WatcherConfig config) {
performOnWatch(config, a -> {
deployWatch(a);
return null;
});
}
public void delete(final WatcherConfig config) {
performOnWatch(config, a -> {
deleteWatch(a);
return null;
});
}
public void performOnWatch(WatcherConfig config, Function<WatchConfig, Void> function) {
for (WatchConfig watchConfig : config.getWatchConfigs()) {
List<WatchConfig> realConfigs = WatchUtils.parseWatchParameter(watchConfig);
for(WatchConfig realWatchConfig : realConfigs) {
function.apply(realWatchConfig);
}
}
}
Run Code Online (Sandbox Code Playgroud)
performOnWatch如果实现streamWatchConfigs替换getWatchConfigs(可能返回集合),则可以使用流简化方法:
public void performOnWatch(WatcherConfig config, Consumer<WatchConfig> consumer) {
config.streamWatchConfigs()
.flatMap(WatchUtils::parseWatchParameters)
.forEach(consumer::accept);
}
performOnWatch(config, this::deployWatch);
performOnWatch(config, this::deleteWatch);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
552 次 |
| 最近记录: |