Java 如何有效地实现抽象类的多个方法?
我需要用3个抽象方法实现一个抽象类Java 如何有效地实现抽象类的多个方法?,java,oop,Java,Oop,我需要用3个抽象方法实现一个抽象类 class Example { abstract boolean func1(); abstract boolean func2(); abstract boolean func3(); } Example createExample(String option1, String option2, , String option2) { if (option1=="something") {
class Example {
abstract boolean func1();
abstract boolean func2();
abstract boolean func3();
}
Example createExample(String option1, String option2, , String option2) {
if (option1=="something") {
define func1 in some way
} else {
define func1 in some other way;
}
depending on option2 hash out the logic for func2;
depending on option3 hash out the logic for func3;
create and return class Example with the definitions of func1, func2 and func3;
}
如何有效地实现此功能?您可以使用供应商实例,您可以执行以下操作:
Example createExample(String option1,
String option2,
String option3) {
// you most likely don't want to use `==` and
// instead `.equals(...)` and a `null` check (prior)
final Supplier<Boolean> f1 = option1 == "something" ? () -> true : () -> false;
final Supplier<Boolean> f2 = option2 == "something" ? () -> true : () -> false;
final Supplier<Boolean> f3 = option3 == "something" ? () -> true : () -> false;
return new Example() {
boolean func1() { return f1.get(); }
boolean func2() { return f2.get(); }
boolean func3() { return f3.get(); }
};
}
您尝试了什么?您尝试了什么?解决方案1:几何爆炸:为每个组合创建单独的代码解决方案2:使用FunctionInterface您可以展示FunctionInterface解决方案吗?我猜这与下面@philipp的答案类似。你认为这有什么问题?我想这是我们能做的最好的选择。另一种选择是有3个不同的接口。这可能更接近接口隔离原则