Skip to content

Instantly share code, notes, and snippets.

@octavian-nita
Created November 28, 2016 13:43
Show Gist options
  • Select an option

  • Save octavian-nita/3ecab674e1a49ae7dbcfd33b7b1ed275 to your computer and use it in GitHub Desktop.

Select an option

Save octavian-nita/3ecab674e1a49ae7dbcfd33b7b1ed275 to your computer and use it in GitHub Desktop.
The Visitor design pattern in Java
import static java.util.Arrays.asList;
interface BaseVisitor {
default void visit(Base base) {
if (base != null) {
base.foo();
System.out.println();
}
}
default void visit(Derived derived) {
if (derived != null) {
derived.foo();
derived.bar();
System.out.println();
}
}
}
class Base {
private static int counter;
final int id = ++counter;
void foo() { System.out.printf("Base(%d)::foo%n", id); }
void accept(BaseVisitor v) { v.visit(this); }
}
class Derived extends Base {
void foo() { System.out.printf("Derived(%d)::foo%n", id); }
void bar() { System.out.printf("Derived(%d)::bar%n", id); }
void accept(BaseVisitor v) { v.visit(this); }
}
public class VPT {
public static void main(String[] args) {
BaseVisitor v = new BaseVisitor() {};
asList(new Base(), new Derived(), new Derived(), new Base()).stream().forEach(b -> b.accept(v));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment