fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.function.*;
  5. import java.lang.*;
  6. import java.io.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. // used in both chains
  14. K1 k1 = new K1();
  15. K2 k2 = new K2();
  16. K3 k3 = new K3();
  17. // construct A chain
  18. Function<A, A> handleA = wrap(k3::handle);
  19. handleA = handleA.compose(wrap(k2::handle));
  20. handleA = handleA.compose(wrap(k1::handle));
  21. // try with A
  22. A sampleA = new A();
  23. handleA.apply(sampleA);
  24. // construct B chain
  25. Function<B,B> handleB = wrap(k3::handle);
  26. handleB = handleB.compose(wrap(k2::handle));
  27. handleB = handleB.compose(wrap(k1::handle));
  28. // try with B
  29. B sampleB = new B();
  30. B result = handleB.apply(sampleB); // you can even get a B result from the whole chain
  31. }
  32. private static <T>Function<T,T> wrap(Consumer<T> consumer) {
  33. return t -> { consumer.accept(t); return t; };
  34. }
  35. }
  36.  
  37. interface S {}
  38. class A implements S {}
  39. class B implements S {}
  40.  
  41. class K1 {
  42. public void handle(S s) { System.out.println("K1 handling S"); }
  43. }
  44.  
  45. class K2 {
  46. public void handle(S s) { System.out.println("K2 handling S"); }
  47. }
  48. class K3 {
  49. public void handle(A a) { System.out.println("K3 handling A"); }
  50. public void handle(B b) { System.out.println("K3 handling B"); }
  51. }
  52.  
Success #stdin #stdout 0.08s 33624KB
stdin
Standard input is empty
stdout
K1 handling S
K2 handling S
K3 handling A
K1 handling S
K2 handling S
K3 handling B