Java 8链lambda

时间:2017-12-12 06:20:58

标签: lambda java-8

我正在玩java lambdas,这是我目前的代码:

public class TypeChecker<T> {
    private T value;
    private Class clazz;
    private UnaryOperator<T> callback;

    private TypeChecker(T value) {
        this.value = value;
    }

    public static TypeChecker<String> when(String v) {
        return new TypeChecker<>(v);
    }

    public static TypeChecker<Integer> when(int v) {
        return new TypeChecker<>(v);
    }

    public TypeChecker<T> is(Class clazz) {
        this.clazz = clazz;
        return this;
    }

    public TypeChecker<T> then(UnaryOperator<T> callback) {
        this.callback = callback;
        return this;
    }

    public void execute() {
        if (clazz.isInstance(value)) {
            callback.apply(value);
        }
    }
}

TypeChecker.when("123").is(String.class).then(s -> {
    return s;
}).execute();

TypeChecker.when(123).is(Integer.class).then(n -> {
    return n;
}).execute();

这里我只是检查instanceOf变量及其工作正常。我想要实现的是这样的:

TypeChecker.when(123)
.is(String.class).then(s -> {
    return s;
})
.is(Integer.class).then(n -> {
    return n;
})
.is(Double.class).then(d -> {
    return d;
}).execute();

现在我如何链接它?我很困惑我应该在哪里保存Clazz&amp; Callbacks?我应该将它存储在地图中并在execute方法中迭代并检查吗?

1 个答案:

答案 0 :(得分:5)

你的问题让我想起lambda expression builder pattern。我将介绍一个新界面来执行<Input focus placeholder="Search..."> <MaskedInput mask={["(",/[1-9]/,/\d/,/\d/,")"," ",/\d/,/\d/,/\d/,"-",/\d/,/\d/,/\d/,/\d/]} guide={true} {...this.props} /> </Input> 操作,并将其添加到is().then()中的Map,如:

TypeChecker

轻松测试并且应该产生您想要的结果:

class Matcher<T> {

  private final Map<Class<?>, UnaryOperator> mapping = new HashMap<>();
  private final T value;

  private Matcher(T value) {
    this.value = value;
  }

  public static <T> Matcher<T> when(T v) {
    return new Matcher<>(v);
  }

  public <S> Condition<S> is(Class<S> clazz) {
    return callback -> {
      mapping.put(clazz, callback);
      return this;
    };
  }

  public void execute() {
    mapping.forEach((key, val) -> {
      if (key.isInstance(value)) {
        val.apply(value);
      }
    });
  }

  interface Condition<S> {
    Matcher<?> then(UnaryOperator<? super S> callback);
  }
}