Last active
September 15, 2015 01:25
-
-
Save jakecoffman/1816900b7cbb78352229 to your computer and use it in GitHub Desktop.
example implementation of the visitor pattern in groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def randomElement | |
// simulate user input, for instance | |
if (new Random().nextInt() % 2 == 0) { | |
randomElement = new Element1() | |
} else { | |
randomElement = new Element2() | |
} | |
new PrinterVisitor().visit(randomElement) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.jakecoffman.visitor | |
interface IVisitor { | |
void visit(Element1 e) | |
void visit(Element2 e) | |
} | |
interface IElement { | |
void accept(IVisitor visitor) | |
} | |
class Element1 implements IElement { | |
String name | |
String element1Specific | |
Element1() { | |
name = "Element1" | |
element1Specific = "specific1" | |
} | |
@Override | |
void accept(IVisitor visitor) { | |
visitor.visit(this) | |
} | |
} | |
class Element2 implements IElement { | |
String name | |
String element2Specific | |
Element2() { | |
name = "Element2" | |
element2Specific = "specific2" | |
} | |
@Override | |
void accept(IVisitor visitor) { | |
visitor.visit(this) | |
} | |
} | |
class PrinterVisitor implements IVisitor { | |
@Override | |
void visit(Element1 e) { | |
println "${e.name} ${e.element1Specific}" | |
} | |
@Override | |
void visit(Element2 e) { | |
println "${e.name} ${e.element2Specific}" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment