今天搬砖时,需要实现类似于以下的业务逻辑
String result;
if(source == 1){
result = "first";
}else if(source == 2){
result = "two";
} else if (source == 3){
result = "three";
}else {
result = "other";
}
突然想到经常看到文章都想要干掉IF,为此我也忍不住做了了一下实现
代码不多,虽然简陋漏,但也算是勉强干掉了IF
public class Chooser<T, V> {
private List<Option> options = new ArrayList<>();
private final T source;
public static <T, V> Chooser<T, V> create(T source) {
return new Chooser<>(source);
}
public Chooser(T source) {
this.source = source;
}
private Chooser(List<Option> options, T source) {
this(source);
this.options = options;
}
public OptionBuilder when(Predicate<T> predicate) {
return new OptionBuilder(predicate);
}
public Optional<V> getAny() {
return this.options.stream()
.filter(option -> option.predicate.test(this.source))
.map(option -> option.value)
.findAny();
}
public Optional<V> getFirst() {
return this.options.stream()
.filter(option -> option.predicate.test(this.source))
.map(option -> option.value)
.findFirst();
}
public V orElse(V other) {
return this.getFirst().orElse(other);
}
class Option {
private final V value;
private final Predicate<T> predicate;
public Option(Predicate<T> predicate, V value) {
this.value = value;
this.predicate = predicate;
}
}
public class OptionBuilder {
private final Predicate<T> predicate;
OptionBuilder(Predicate<T> predicate) {
this.predicate = predicate;
}
public Chooser<T, V> then(V value) {
Chooser.this.options.add(new Option(predicate, value));
return new Chooser<T, V>(Chooser.this.options, Chooser.this.source);
}
}
}
验证一下成果
public static void main(String[] args) {
String result = Chooser.<Integer, String>create(1)
.when(value -> value == 1)
.then("first")
.when(value -> value == 2)
.then("two")
.when(value -> value == 3)
.then("three")
.orElse("other");
Assert.isTrue(Objects.equal(result, "first"), "结果不是first");
String result2 = Chooser.<Integer, String>create(4)
.when(value -> value == 1)
.then("first")
.when(value -> value == 2)
.then("two")
.when(value -> value == 3)
.then("three")
.orElse("other");
Assert.isTrue(Objects.equal(result2, "other"), "结果不是other");
}
结果符合预期,the end