Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. package test;
  2.  
  3. public static void main(String[] args) {
  4.  
  5. // Create a visitable collection
  6. FooCollection c = new FooCollection();
  7.  
  8. // Add some members
  9. c.add(new Foo());
  10. c.add(new Bar());
  11.  
  12. // Visit
  13. c.accept(new IVisitor<Foo>() {
  14.  
  15. public void visit(Foo foo) {
  16. System.out.println("Foo");
  17. }
  18.  
  19. public void visit(Bar bar) {
  20. System.out.println("Bar");
  21. }
  22. });
  23. }
  24.  
  25. public static class Foo {
  26. }
  27.  
  28. public static class Bar extends Foo {
  29. }
  30.  
  31. public static interface IVisitor<T> {
  32.  
  33. public void visit(T object);
  34. }
  35.  
  36. public static class FooCollection {
  37.  
  38. private final ArrayList<Foo> m_list = new ArrayList<>();
  39.  
  40. public void accept(IVisitor<Foo> visitor) {
  41. for (Foo foo : m_list) {
  42. visitor.visit(foo);
  43. }
  44. }
  45.  
  46. public void add(Foo foo) {
  47. m_list.add(foo);
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement