Mediator Design pattern Groovy implementation


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

Mediator design pattern implemented in Groovy (based upon http://www.javacamp.org/designPattern/).


Copy this code and paste it in your HTML
  1. // The mediator class which connects all the colleges (buttons in this case)
  2. // and updates them all in reaction to informations from any of them
  3. package design.patterns.mediator
  4. public class Mediator {
  5. def show
  6. def buttons = []
  7.  
  8. void registerButton(b) {
  9. buttons << b
  10. }
  11. void registerDisplay(d) {
  12. show = d
  13. }
  14. void mediate(disable, text) {
  15. buttons.each {
  16. if (it == disable) {
  17. it.enabled - false
  18. }
  19. else {
  20. it.enabled = true
  21. }
  22. }
  23. show.setText(text)
  24. }
  25. }
  26.  
  27. // The demo UI which demonstrates the usage
  28. package design.patterns.mediator.ui
  29. import groovy.swing.SwingBuilder
  30. import design.patterns.mediator.Mediator
  31.  
  32. public class MediatorDemo {
  33.  
  34. public static void main(String[] args) {
  35. def Mediator mediator = new Mediator()
  36. def frame = new SwingBuilder().frame() {
  37. panel() {
  38. label(text: 'just starting') {mediator.registerDisplay(current)}
  39. button() {
  40. mediator.registerButton(current)
  41. action(name: 'view', closure: {mediator.mediate(current, 'viewing ..')})
  42. }
  43. button() {
  44. mediator.registerButton(current)
  45. action(name: 'book', closure: {mediator.mediate(current, 'booking ..')})
  46. }
  47.  
  48. button() {
  49. mediator.registerButton(current)
  50. action(name: 'search', closure: {mediator.mediate(current, 'searching ..')})
  51. }
  52.  
  53. }
  54. }
  55. frame.setSize(400, 200);
  56. frame.setVisible(true);
  57. }
  58.  
  59. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.