对于这种策略模式,我是否适当地使用JavaLambda?

对于这种策略模式,我是否适当地使用JavaLambda?,java,lambda,Java,Lambda,我使用lambda expression+函数来实现策略模式,我是否正确且适当地使用它 public void deploy(WatcherConfig config) { performOnWatch(config, a -> { deployWatch(a); return null; }); } public void delete(final WatcherConfig config) { performOnWatch(co

我使用lambda expression+函数来实现策略模式,我是否正确且适当地使用它

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);
        }
    }
}
public void部署(WatcherConfig配置){
performOnWatch(配置,a->{
部署观察(a);
返回null;
});
}
公共作废删除(最终WatcherConfig配置){
performOnWatch(配置,a->{
(一);
返回null;
});
}
public void performOnWatch(WatcherConfig配置,函数){
for(WatchConfig WatchConfig:config.getWatchConfigs()){
List realConfigs=WatchUtils.parseWatchParameter(watchConfig);
for(WatchConfig realWatchConfig:realConfigs){
apply(realWatchConfig);
}
}
}

似乎是合法的。我唯一想改变的是使用
消费者
而不是
功能
。它将简化方法签名以及策略实现(无需从策略中
返回null

另外,如果
deleteWatch()
deployWatch()
返回空值,并且如果您将使用
消费者
则代码可以重写为:

performOnWatch(config, this::deployWatch);

performOnWatch(config, this::deleteWatch);

如果实现
streamWatchConfigs
来替换
getWatchConfigs
(可能返回一个集合),则可以使用streams简化
performOnWatch
方法:

public void performOnWatch(WatcherConfig配置,使用者){
config.streamWatchConfigs()
.flatMap(WatchUtils::parseWatchParameters)
.forEach(消费者::接受);
}
performOnWatch(配置,this::deployWatch);
performOnWatch(配置,this::deleteWatch);

每次你使用“模式”这个词时,你都在把自己挖进一个可怕的心理洞。这就是为什么我希望那本模式书从来没有被写过。停止思考模式。忘记他们的名字。考虑您需要完成哪些工作,以及该语言为您提供了哪些工具,以结合灵活性、代码可读性和性能的方式解决问题。模式是精神支柱。如果您足够聪明,能够正确使用模式,则不需要模式。如果你不这样做,模式对你的伤害将大于帮助。

好吧,它有效吗?如果是,当然。若并没有,那个就并没有。是否使用流是个人喜好的问题,但消费者肯定比这里的函数更好。这很有趣。你能推荐一些更深入的阅读吗?对我来说,这只是试图推销常识的味道,我对此过敏。你也看到这个问题了吗
public void performOnWatch(WatcherConfig config, Consumer<WatchConfig> consumer) {
    config.streamWatchConfigs()
        .flatMap(WatchUtils::parseWatchParameters)
        .forEach(consumer::accept);
}

performOnWatch(config, this::deployWatch);
performOnWatch(config, this::deleteWatch);