Decorator Design Pattern Groovy


/ Published in: Groovy
Save to your folder(s)

Decorator design pattern implemented in Groovy, two implementation are provided, the first is naive and not general, the second is MOP based and can be used in much more scenarios.


Copy this code and paste it in your HTML
  1. // the decorated class
  2. package design.patterns.decorator
  3.  
  4. class Logger {
  5. def log(text) {
  6. println(text)
  7. }
  8. }
  9.  
  10. // the naive implementation
  11. package design.patterns.decorator
  12.  
  13. class LowerCaseLogger extends Logger {
  14.  
  15. def logger
  16.  
  17. LowerCaseLogger(log) {
  18. logger = log
  19. }
  20.  
  21. def log(text) {
  22. logger.log(text.toLowerCase())
  23. }
  24.  
  25.  
  26. public static void main(String[] args) {
  27. def logger = new LowerCaseLogger(new Logger())
  28. logger.log('HELLO DECORATION')
  29. }
  30. }
  31.  
  32. // the more general implementation
  33. package design.patterns.decorator
  34.  
  35. class GenericLowerLogger {
  36. private delegate
  37.  
  38. GenericLowerLogger(delegate) {
  39. this.delegate = delegate
  40. }
  41. def invokeMethod(String name, args) {
  42. def newargs = args.collect {arg ->
  43. if (arg instanceof String) return arg.toLowerCase()
  44. }
  45. delegate.invokeMethod(name, newargs)
  46. }
  47.  
  48. public static void main(String[] args) {
  49. def logger = new GenericLowerLogger(new Logger())
  50. logger.log('HELLO DECORATION')// hello decoration
  51. }
  52. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.