自定义或者Java中的操作

对于 Java 项目,我创建了一个自定义布尔类(名为 Result),它可以具有三个值:True、False 或 Undefined。我定义了两个函数:“or”和“and”,规则如下:


    public static Result or(Result r1, Result r2) {

        if(r1.isTrue() || r2.isTrue()){

            return V(); //new Result with value "True";

        } else if(r1.isUndefined() || r2.isUndefined()) {

            return U(); //new Result with value "Undefined";

        }  else {

            return F(); //new Result with value "False";

        }

    }


    public static Result and(Result r1, Result r2) {

        if(r1.isFalse() || r2.isFalse()){

            return F(); //new Result with value "False";

        } else if(r1.isUndefined() || r2.isUndefined()) {

            return U();//new Result with value "Undefined";

        }  else {

            return V(); //new Result with value "True";

        }

    }

这是可行的,但在很多情况下,它效率不高,因为我需要在计算“or”或“and”的返回之前计算两个 Result 的值:


如果我做


if(f1() || f2()){


}

并且f1()的结果为True,f2()将永远不会被执行以节省计算时间。


是否有解决方案可以使我的自定义类具有相同的行为?


慕虎7371278
浏览 86回答 1
1回答

守着星空守着你

您可以使用Supplier以获得类的“延迟”执行Result:public static Result or(Supplier<Result> r1Supplier, Supplier<Result> r2Supplier) {&nbsp; &nbsp; &nbsp; &nbsp; Result r1 = r1Supplier.get();&nbsp; &nbsp; &nbsp; &nbsp; if(r1.isTrue()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return V(); //new Result with value "True";&nbsp; &nbsp; &nbsp; &nbsp; } else if(r1.isUndefined()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return U(); //new Result with value "Undefined";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // only here you need to handle r2&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Result r2 = r2Supplier.get();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(r2.isTrue()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return V(); //new Result with value "True";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else if(r2.isUndefined()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return U(); //new Result with value "Undefined";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return F();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }它可以稍微清理一下并排序得更好,但你会掌握它的窍门
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java