Advertisement
zinch

Visitor pattern from "Groovy in Action"

Sep 30th, 2014
472
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 0.64 KB | None | 0 0
  1. class Drawing {
  2.     List shapes
  3.     def accept(Closure yield) { shapes.each { it.accept(yield) } }
  4. }
  5.  
  6. class Shape {
  7.     def accept(Closure yield) { yield(this) }
  8. }
  9.  
  10. class Square extends Shape {
  11.     def width
  12.     def area() { width ** 2 }
  13. }
  14.  
  15. class Circle extends Shape {
  16.     def radius
  17.     def area() { Math.PI * radius ** 2 }
  18. }
  19.  
  20. def picture = new Drawing(shapes:[new Square(width:1), new Circle(radius:1)])
  21. def total = 0
  22.  
  23. picture.accept { total += it.area() }
  24.  
  25. println "The shapes in this drawing cover an area of $total"
  26. println "The individual contributions are: "
  27. picture.accept { println it.class.name + ":" + it.area() }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement