gpt4 book ai didi

java - 在这种情况下用策略模式替换复杂的条件语句是否有意义

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:41 28 4
gpt4 key购买 nike

我有一个值,只有在满足某些条件时才需要从方法返回,否则我必须返回 null。
该方法正在获取 2 个 boolean 参数,根据这些参数调用进一步的方法来检查其他一些条件。

Call method1, then method2 -> if (param1 && param2) == true;
Don't call any method-> if (!param1 && !param2) == true;
Call only method1 -> if only param1 == true;
Call only method2 -> if only param2 == true; //Method2 is an expensive operation.

所以,为了满足这个要求,我写了一段代码,如下所示 -

value = doSomeProcessingToGetValue(); //Not an expensive operation
if(param1 && param2) //both are true {
if(method1() != null) { // if method1 return true then move ahead
if(method2() != null) { //if method2 return true then move ahead (Expensive operation)
return value; //Means all the conditions are satisfied now
}
}
}
else if(!param1 && !param2) //both are false {
return value; //No need to check for any condition
}
else if(param1) //Means param1 is true {
if(method1()!=null) {// if method1 return true then move ahead
return value; //Means all the conditions are satisfied now
}
}
else { //Means param2 is true
if(method2()!=null) {// if method2 return true then move ahead(Expensive operation)
return value; //Means all the conditions are satisfied now
}
}
return null;

我对上述方法有 2 个顾虑 -

可扩展性 - 此解决方案不可扩展,因为将来可能需要检查更多参数及其各自要调用的方法。所以,没有。 if else 检查的数量将随着每个参数的增加呈指数增长。
不优雅 - 由于有太多的条件检查,它看起来不是很优雅。为了让它更优雅,我正在考虑应用Strategy pattern
Strategy pattern approach 说到高层次,我将为给定的每个条件创建具体的类多于。因此,对于上面的代码,将有四个具体类。我将遍历所有具体类并检查它们是否满足条件并相应地返回值。
我的疑问是使用策略模式来满足这个要求是否有意义,因为这个解决方案在可伸缩性方面也表现不佳。
或者是否有任何更好的方法在可扩展性方面会有好处。

最佳答案

策略模式通常用于在运行时选择算法。所以,这可能是个不错的选择。

但是您写过“我将遍历所有具体类并检查它们是否满足条件”。您无需遍历实现。您可以使用例如 factory 在运行时创建策略实现:

public Strategy getStrategy(boolean param1, boolean param2) {

if (param1) {
if (param2) {
return value -> method1() != null && method2() != null ? value : null;
} else {
return value -> method1() != null ? value : null;
}
} else {
if (param2) {
return value -> method2() != null ? value : null;
} else {
return value -> value;
}
}
}

为了紧凑,我使用了 lambda,这只是示例。策略界面是:

interface Strategy {
Object getValue(Object value);
}

可以通过构造函数参数或设置方法将策略注入(inject)到您的主类中。如您所见,工厂成为您条件的另一个地方。因此,至少有一些条件进入了具体实现。

此外,replace condition with polymorphism重构模式和 stackoverflow discussion about it可能会有帮助。

还有一件事。看起来您的类实例的状态取决于 param1 和 param2。因此,其他设计解决方案可能是 finite state machine

关于java - 在这种情况下用策略模式替换复杂的条件语句是否有意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54732755/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com