是的,这可以在 Java 7 中轻松完成,使用 Java 8 甚至更干净。
参数给你的method
方法应该是java.util.function.Supplier<T>
以及你的参数until
方法应该是java.util.function.Predicate<T>
.
然后,您可以使用方法引用或 lambda 表达式来创建 Poller,如下所示:
myMethodPoller.poll(pollDurationInteger, intervalInMillisecond)
.method(payment::getStatus)
.until (paymentStatus -> paymentStatus.getValue().equals("COMPLETED"))
.execute();
附带说明一下,如果您要使用 Java 8,我建议使用java.time.Duration
而不是一个整数来表示轮询持续时间和间隔。
我还建议研究一下https://github.com/rholder/guava-retrying https://github.com/rholder/guava-retrying这是一个你也许可以使用的库。如果没有,它可能会对您的 API 产生很好的启发,因为它具有良好流畅的 API。
编辑:
更新问题后,这是一个简单的实现。我留了一些部分作为待办事项供您完成。
import java.time.Duration;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class MethodPoller<T> {
Duration pollDurationSec;
int pollIntervalMillis;
private Supplier<T> pollMethod = null;
private Predicate<T> pollResultPredicate = null;
public MethodPoller() {
}
public MethodPoller<T> poll(Duration pollDurationSec, int pollIntervalMillis) {
this.pollDurationSec = pollDurationSec;
this.pollIntervalMillis = pollIntervalMillis;
return this;
}
public MethodPoller<T> method(Supplier<T> supplier) {
pollMethod = supplier;
return this;
}
public MethodPoller<T> until(Predicate<T> predicate) {
pollResultPredicate = predicate;
return this;
}
public T execute()
{
// TODO: Validate that poll, method and until have been called.
T result = null;
boolean pollSucceeded = false;
// TODO: Add check on poll duration
// TODO: Use poll interval
while (!pollSucceeded) {
result = pollMethod.get();
pollSucceeded = pollResultPredicate.test(result);
}
return result;
}
}
使用示例:
import static org.junit.Assert.assertTrue;
import java.util.UUID;
import org.junit.Test;
public class MethodPollerTest
{
@Test
public void test()
{
MethodPoller<String> poller = new MethodPoller<>();
String uuidThatStartsWithOneTwoThree = poller.method(() -> UUID.randomUUID().toString())
.until(s -> s.startsWith("123"))
.execute();
assertTrue(uuidThatStartsWithOneTwoThree.startsWith("123"));
System.out.println(uuidThatStartsWithOneTwoThree);
}
}