如何高效实现抽象类的多个方法?

huangapple go评论63阅读模式
英文:

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&lt;Boolean&gt;` instances, you could do:

Example createExample(String option1,
String option2,
String option3) {

// you most likely don&#39;t want to use `==` and 
// instead `.equals(...)` and a `null` check (prior)
final Supplier&lt;Boolean&gt; f1 = option1 == &quot;something&quot; ? () -&gt; true : () -&gt; false;
final Supplier&lt;Boolean&gt; f2 = option2 == &quot;something&quot; ? () -&gt; true : () -&gt; false;
final Supplier&lt;Boolean&gt; f3 = option3 == &quot;something&quot; ? () -&gt; true : () -&gt; false;

return new Example() {
    boolean func1() { return f1.get(); }
    boolean func2() { return f2.get(); }
    boolean func3() { return f3.get(); }
};

}


</details>



huangapple
  • 本文由 发表于 2020年9月24日 00:44:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64032595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定