Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The visitor pattern is a pattern for communication and collaboration between two union patterns: a "host" union and a "visitor" union. An abstract visitor is usually defined as an interface or an abstract class in Java. It has a separate method for each of the concrete variant of the host union. The abstract host has a method (called the "hook") to "accept" a visitor and leaves it up to each of its concrete variants to call the appropriate visitor method. This "decoupling" of the host's structural behaviors from the extrinsic algorithms on the host permits the addition of infinitely many external algorithms without changing any of the host union code. This extensibility only works if the taxonomy of the host union is stable and does not change. If we have to modify the host union, then we will have to modify ALL visitors as well! The following is diagram showing the overall architecture of the visitor design pattern. This type of diagram is called the UML (Unified Modeling Language) class diagram.

https://wiki.rice.edu/display/CSWIKI/211lab09/hostVisitors.png

Applied to the list structure, the visitor pattern takes the following coding pattern.

...

  1. Write a visitor called Length to compute the length of an IntList.#* Write a non-tail recursive version (using direct recursion).
    • Write a tail-recursive version using a helper visitor (in place of a helper method).
      2 Write a visitor called ProdNums that returns the product of the number in the list, using a tail recursive helper visitor.
      3 Write a visitor called Reverse that reverses the list using a tail-recursive helper visitor.
      4 Write a visitor called ListString that uses as tail recursive visitor as done in the method listString.
      5 Write a visitor called MakePalindrome that returns a list consisting of the input list and its mirror around the last element, using a (non tail-recursive) helper with an accumulator. For example, (1, 2, 3).accept(MakePalindrome.ONLY) returns the list (1, 2, 3, 2, 1) .

...