Skip to content

Instantly share code, notes, and snippets.

@rac021
Created June 12, 2023 07:41
Show Gist options
  • Save rac021/8465ae721ab78e4e3ecf4abdd40880c3 to your computer and use it in GitHub Desktop.
Save rac021/8465ae721ab78e4e3ecf4abdd40880c3 to your computer and use it in GitHub Desktop.
package dsl;
/**
*
* @author ryahiaoui
*/
import java.util.function.Function;
public class Dsl {
public interface selectableAction {}
public static class Select implements Function<String, selectableAction > {
@Override
public Copy apply(String s) {
return new Copy() ;
}
}
public static class Cut implements Function<selectableAction, selectableAction > , selectableAction {
@Override
public Copy apply(selectableAction s) {
return new Copy() ;
}
}
public static class Copy implements Function<Select, Past> , selectableAction {
@Override
public Past apply(Select s) {
return new Past();
}
}
public static class Past implements Function<selectableAction, Void> {
@Override
public Void apply(selectableAction t) {
System.out.println("Do whatever with selectable !!");
return null;
}
}
// Fonction qui split une string sur le séparateur "," et renvoie un tableau de string
private static Function<String, String[]> split = s -> s.split(",");
// Fonction qui concatène un tableau de string
private static Function<String[], String> concat = arr -> String.join("", arr);
// Méthode qui renvoie une fonction en fonction d'un paramètre
public static Function getFunction(int param) {
// Utilisation d'une expression switch
return switch (param) {
case 1 -> new Select() ;
case 2 -> new Cut() ;
case 3 -> new Copy() ;
case 4 -> new Past() ;
case 5 -> split ;
case 6 -> concat ;
default -> s -> s ;
};
}
// Méthode principale pour tester les chaines de fonctions
public static void main(String[] args) {
// OK
new Select().andThen(new Past()).apply("Text to Copy...");
new Select().andThen(new Cut()).andThen(new Cut()).andThen(new Past()).andThen(new Past()) ;
// Forbidden
new Select().andThen(new Select()) ;
// Forbidden
new Cut().andThen(new Select()) ;
// Forbidden
new Past().andThen(new Select()) ;
/*
// andThen
Function<String, Integer> chain1 = getFunction(1).andThen(getFunction(2));
// compose
Function<String, String> chain2 = getFunction(4).compose(getFunction(1));
// Test des chaines de fonctions
String input = "1,2,3,4";
System.out.println(chain1.apply(input)); // 10
System.out.println(chain2.apply(input)); // 1234
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment