Created
November 28, 2016 13:43
-
-
Save octavian-nita/3ecab674e1a49ae7dbcfd33b7b1ed275 to your computer and use it in GitHub Desktop.
The Visitor design pattern in Java
This file contains hidden or 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
| 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