英文:
How do I implement multiple methods of an abstract class efficiently?
问题
我需要实现一个带有3个抽象方法的抽象类
    abstract class Example {
        abstract boolean func1();
        abstract boolean func2();
        abstract boolean func3();
    }
    
    Example createExample(String option1, String option2, String option3) {
        if (option1.equals("something")) {
            // 以某种方式定义 func1
        } else {
            // 以另一种方式定义 func1
        }
    
        // 根据 option2 的情况编写 func2 的逻辑;
    
        // 根据 option3 的情况编写 func3 的逻辑;
        
        // 创建并返回带有 func1、func2 和 func3 定义的 Example 类;
    }
如何高效实现这个呢?
英文:
I need to implement an abstract class with 3 abstract methods
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;
}
How do I implement this efficiently?
答案1
得分: 1
可以使用`Supplier<Boolean>`实例,你可以这样做:
Example createExample(String option1,
String option2,
String option3) {
// 你最好不要使用 `==`,而是使用 `.equals(...)` 和空值检查(在之前)
final Supplier<Boolean> f1 = option1.equals("something") ? () -> true : () -> false;
final Supplier<Boolean> f2 = option2.equals("something") ? () -> true : () -> false;
final Supplier<Boolean> f3 = option3.equals("something") ? () -> true : () -> false;
return new Example() {
    boolean func1() { return f1.get(); }
    boolean func2() { return f2.get(); }
    boolean func3() { return f3.get(); }
};
}
<details>
<summary>英文:</summary>
You can use `Supplier<Boolean>` instances, you could do:
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(); }
};
}
</details>
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论