Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中是否有确保调用该方法的功能_Java_Builder - Fatal编程技术网

Java中是否有确保调用该方法的功能

Java中是否有确保调用该方法的功能,java,builder,Java,Builder,我正在使用类似于builder/fluid API的模式来配置一些计时服务。我知道它不是一个典型的建筑商,但它看起来很漂亮,我想保持这种风格 它看起来像: Action someAction = getAction(); someAction.shouldRunEvery(5).seconds(); 其中最后一个动词可以是秒()、分钟()、毫秒()等。 链中最后一个方法中的代码实际上将更改写入存储库。 典型的错误(尽管我知道内部结构,但我不止一次这样做)是使用这样的方法: someAction

我正在使用类似于builder/fluid API的模式来配置一些计时服务。我知道它不是一个典型的建筑商,但它看起来很漂亮,我想保持这种风格

它看起来像:

Action someAction = getAction();
someAction.shouldRunEvery(5).seconds();
其中最后一个动词可以是秒()、分钟()、毫秒()等。 链中最后一个方法中的代码实际上将更改写入存储库。 典型的错误(尽管我知道内部结构,但我不止一次这样做)是使用这样的方法:

someAction.shouldRunEvery(10);
someAction.shouldRunEvery(seconds(5));
interface PreAction{ ActionUnit shouldRunEvery (int time);}
interface ActionUnit { Action seconds(); Action minutes(); ... etc.}
有没有办法确保在对象上调用接口的函数? 我可以使用java 8/9的任何功能和/或其他库

补充1: 流体API的生产方式:

interface Action{ ActionUnit shouldRunEvery (int time);}
interface ActionUnit { void seconds(); void minutes(); ... etc.}
补充2: 我曾试图调查例外情况,但不知道如何将它们缝合在上面并保持整洁

补充3: 最好的答案可能是将API更改为以下内容:

someAction.shouldRunEvery(10);
someAction.shouldRunEvery(seconds(5));
interface PreAction{ ActionUnit shouldRunEvery (int time);}
interface ActionUnit { Action seconds(); Action minutes(); ... etc.}

但是在这种情况下,我失去了流动性。

您可以强制调用其中一个时间单位方法,方法是让它们返回一个动作,让
getAction()
返回的不是动作,而是一个新生的对象(例如“PreAction”):

因此,接口将如下所示:

someAction.shouldRunEvery(10);
someAction.shouldRunEvery(seconds(5));
interface PreAction{ ActionUnit shouldRunEvery (int time);}
interface ActionUnit { Action seconds(); Action minutes(); ... etc.}

现在,当您忘记了时间单位时,您将得到一个不能用作操作的PreAction对象。

在Java中没有好的方法,但它仍然是可能的。您可以在这里找到“安全构建器”示例。 此示例使用Java泛型是图灵完备的这一事实。您可以阅读原文(仅俄文)


但我担心它的语法对于现实生活来说太糟糕了。

这个问题实际上可能更适合软件工程SE。我们可以有一个MOD移动吗?你是否考虑改变<代码>应该是“<代码/ >签名”,这样做:“代码> BoDRunNUNE(5,TimeNo.MILL)< /Cord>?恐怕你不能强制一个方法在java中被调用。只有当返回类型是您期望的返回类型时,您才能知道您已正确结束。这就是说,最好让
shouldlrunevery()
返回类似
ActionBuilder
的内容,
seconds()
返回
Action
。建设者就是这样做的。有一些方法可以绕过它,例如将秒设为默认单位,并使用
.minutes()调用它。
只是用来更改默认单位,允许您跳过该单位,只需调用
shouldlrunevery(5)
。如果你记录你的图书馆,应该没有问题。作为上述答案中描述的俄语文章的作者,我想澄清一些事情。它不是原始版本,它基于以下出版物:。这份出版物是英文的,所以你可以真正地阅读它并了解发生了什么。@Anton为什么?答案是