fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Visitors
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. List<K> handlers = Arrays.asList(new K1(), new K2(), new K3());
  13. S sample = new A();
  14. for (K visitor : handlers) {
  15. sample.visit(visitor);
  16. }
  17. sample = new B();
  18. for (K visitor : handlers) {
  19. sample.visit(visitor);
  20. }
  21. }
  22. }
  23.  
  24. interface K {
  25. void handle(A a);
  26. void handle(B b);
  27. }
  28. class A implements S {
  29. public void visit(K visitor) { visitor.handle(this); }
  30. }
  31. class B implements S {
  32. public void visit(K visitor) { visitor.handle(this); }
  33. }
  34.  
  35. interface S {
  36. void visit(K visitor);
  37. }
  38. class K1 implements K {
  39. public void handle(A a) { System.out.println("K1 handling A"); }
  40. public void handle(B b) { System.out.println("K1 handling B"); }
  41. }
  42. class K2 implements K {
  43. public void handle(A a) { System.out.println("K2 handling A"); }
  44. public void handle(B b) { System.out.println("K2 handling B"); }
  45. }
  46. class K3 implements K {
  47. public void handle(A a) { System.out.println("K3 handling A"); }
  48. public void handle(B b) { System.out.println("K3 handling B"); }
  49. }
Success #stdin #stdout 0.06s 32576KB
stdin
Standard input is empty
stdout
K1 handling A
K2 handling A
K3 handling A
K1 handling B
K2 handling B
K3 handling B