我通常采用 Are booleans as method arguments unacceptable? 中建议的 Enum 参数并使用策略模式来实现它。
但是,我现在有一个复杂的逻辑,我无法移动到枚举中,因为没有非静态枚举,并且需要将大量变量复制到枚举中的方法中或从枚举中的方法中复制出来。如果我在代码中使用开关而不是策略模式,那么除了简单明了之外,我似乎失去了所有好处。
对于这个特定的方法,只能有两种可能性,那么 boolean 参数会更容易被接受吗? (如果使用枚举,我们的编码标准要求我处理任何未知的枚举,这在这种情况下似乎是不必要的。)也许我可以将 boolean 值放入常量中并使用常量调用方法?
编辑:
复杂的逻辑是专有代码,但它类似于
public void method(A a, B b, boolean replaceMe) {
// Create and prepare local variables c, d, e, f, g;
if (replaceMe) {
// doSomethingWith a, b, c, d, e and return e, f, g
} else {
// doSomethingElseWith a, b, c, d, e and return e, f, g
}
// Process e, f, g further
}
最佳答案
您可以再次使用策略模式
public interface DoSomethingWithA2GStrategy { // horrible name I know ;)
void doSomething(A2GParameterContainer params);
}
对于容器,您创建如下内容:
public class A2GParameterContainer {
TypeOfA a;
// ...
TypeOfG g;
//getters and setters
}
然后稍微修改你的方法并传入具体策略
public void method(A a, B b, DoSomethingWithA2GStrategy strategy) {
// Create and prepare local variables c, d, e, f, g;
A2GParameterContainer params = new A2GParameterContainer();
params.setA(a);
// ...
params.setG(g);
strategy.doSomething(params);
// take e, f, g from the container
// Process e, f, g further
}
关于java - 替换不能使用枚举的 boolean 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17446479/