mardi 12 juillet 2016

Java Generics Type DSL with Builder Pattern

I try to create a DSL Java API with the Builder Pattern on Generics Type.

I have the following class:

public class Rule<T> {

  private Predicate<T> condition;

  public ConditionBuilder<T> when() {
    return new ConditionBuilder<>(this);
  }

  //setter and getter 

}

and the following ConditionBuilder class:

public class ConditionBuilder<T> {

  private Rule<T> parent;

  public ConditionBuilder(Rule<T> parent) {
    this.parent = parent;
  }

  public ConditionBuilder<T> condition1() {
    parent.setCondition(l -> l == 0); // I would like an Integer
    return this;
  }

  public ConditionBuilder<T> condition2() {
    parent.setCondition(l -> l.length() > 3); // I would like a String
    return this;
  }

}

I try to find a solution to set the Generic Type on the fly as an Integer (resp. String) for the condition1 (resp. condition2).

Is there any Pattern or solution to avoid doing instanceof checking ?

Aucun commentaire:

Enregistrer un commentaire