public class ChoiceUtil<T, K, U> {
private final T t;
private U u;
private final AtomicBoolean isStop = new AtomicBoolean(false);
private ChoiceUtil(T t) {
this.t = t;
}
public static <T, K, U> ChoiceUtil<T, K, U> of(T t) {
return new ChoiceUtil<>(t);
}
public ChoiceUtil<T, K, U> iF(Predicate<? super T> predicate, Function<? super T, ? extends U> f) {
if (!isStop.get()) {
isStop.set(predicate.test(t));
u = isStop.get() ? f.apply(t) : null;
}
return this;
}
public ChoiceUtil<T, K, U> iF(Predicate<? super T> predicate, K k, Function<? super K, ? extends U> f) {
if (!isStop.get()) {
isStop.set(predicate.test(t));
u = isStop.get() ? f.apply(k) : null;
}
return this;
}
public ChoiceUtil<T, K, U> finallyElse(Function<? super T, ? extends U> f) {
if (!isStop.get()) {
u = f.apply(t);
isStop.set(true);
}
return this;
}
public ChoiceUtil<T, K, U> finallyElse(K k, Function<? super K, ? extends U> f) {
if (!isStop.get()) {
u = f.apply(k);
isStop.set(true);
}
return this;
}
public void peekFinallyElse(Consumer<? super T> a) {
if (!isStop.get()) {
a.accept(t);
isStop.set(true);
}
}
public void peekFinallyElse(K k, Consumer<? super K> a) {
if (!isStop.get()) {
a.accept(k);
isStop.set(true);
}
}
public ChoiceUtil<T, K, U> peekIf(Predicate<? super T> predicate, Consumer<? super T> a) {
if (!isStop.get()) {
isStop.set(predicate.test(t));
if (isStop.get()) {
a.accept(t);
}
}
return this;
}
public ChoiceUtil<T, K, U> peekIf(Predicate<? super T> predicate, K k, Consumer<? super K> a) {
if (!isStop.get()) {
isStop.set(predicate.test(t));
if (isStop.get()) {
a.accept(k);
}
}
return this;
}
public U result() {
return u;
}
public static void main(String[] args) {
String a = "555";
String b = "333";
/*Object result = ChoiceUtil.of(a)
.iF("1"::equals, r -> "if 1")
.iF("2"::equals, r -> "else if 2")
.iF("3"::equals, r -> "else if 3")
.iF("4"::equals, b, "222"::equals)
.finallyElse(b, "333"::equals)
.finallyElse(r -> "else 4")
.result();
System.out.println(result);*/
ChoiceUtil.of(a)
.peekIf("1"::equals, r -> System.out.println("peek if 1"))
.peekIf("4"::equals, b, System.out::println)
.peekIf("2"::equals, r -> System.out.println("peek else if 2"))
.peekIf("3"::equals, r -> System.out.println("peek else if 3"))
.peekFinallyElse(b, System.out::println);
//.peekFinallyElse(r -> System.out.println("peek else 4"));
}
}
【面向对象编程】参考 vavr 自己写的一个简化 if...else 的对象封装, 有问题请指正
最新推荐文章于 2022-10-26 09:04:18 发布