This repository contains simple demo of visitor pattern — a way to organize code that:
-
Has fixed (or rarely changing) hierarchy of types
-
Expects a lot of new algorithms working against these types to be introduced
The repository showcases the problem from a little different point of view: necessity of this organization in Java compared to Groovy. The problem raised there is to process all subclasses of the hierarchy differently in a given algorithm — print in this case.
All demonstrations contain at least two files:
-
Any
— it has aninterface
Any
and three implementations:Ghost
,Flower
andUnicorn
-
Printer
which contains an algorithm to process them, in this case it simply prints the type and an Emoji
The intent there is to the following output:
👻 - Ghost
🌺 - Flower
🦄 - Unicorn
-
Naive implementation in the
src/main/java/com/caco3/visitor/java/unvisited
directory (thecom.caco3.visitor.java.unvisited
package) attempts to do it using method overloads and fails. -
Code written in
src/main/groovy/com/caco3/visitor/groovy
does the same as Java, but does not fail, due to the dynamic nature of the language it is written in — Groovy. -
The
com.caco3.java.visitor
package finally achieves the original goal in Java leveraging the visitor pattern.
The language employs multiple dispatch — the mechanism when not only the type of the receiver of the method call inspected to choose a target method, but something else, in case of groovy argument types are inspected too. The method selection algorithm is precisely described in the documentation.
Simply speaking, we do not need visitors there, the behavior provided as is. [1].
So the demo simply prints:
👻 - Ghost
🌺 - Flower
🦄 - Unicorn
@CompileStatic