Skip to content

Instantly share code, notes, and snippets.

@jakecoffman
Last active September 15, 2015 01:25
Show Gist options
  • Save jakecoffman/1816900b7cbb78352229 to your computer and use it in GitHub Desktop.
Save jakecoffman/1816900b7cbb78352229 to your computer and use it in GitHub Desktop.
example implementation of the visitor pattern in groovy
def randomElement
// simulate user input, for instance
if (new Random().nextInt() % 2 == 0) {
randomElement = new Element1()
} else {
randomElement = new Element2()
}
new PrinterVisitor().visit(randomElement)
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