Iterators over a composite have limited value, because they
treat every type of node the same.
How to write a function over a composite?
There are two things that vary here: which function and
which type of node.
-
interpreter:
-
Method in each node for each function (as usual).
-
Hard to add new functions; easy to add new node types.
-
This is the "normal" OO style for a composite.
-
typecase:
-
One static class per function; define a static helper
method for each node type; use
instanceOf
and casting to determine node type.
-
Hard to add new node types; easy to add new functions.
-
Class names and attributes must be public.
-
Languages such as ML and
scala
have support for typecase, making it more
attractive.
-
visitor:
-
One object class per function; define an object method
for each node type; use double dispatch.
-
Hard to add new node types; easy to add new functions.
-
Class names and attributes may be private.