如何有效地实现抽象类的多个方法



我需要用3个抽象方法实现一个抽象类

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;
}

我如何有效地实现这一点?

您可以使用Supplier<Boolean>实例,您可以执行以下操作:

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(); }
};
}

最新更新