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.pngImage Removed
Image Added

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

Code Block
/**
 * Abstract list structure.
 */
abstract class IntList {
    abstract Object accept(IntListVisitor v);

    ConsIntList cons(int n) {
        return new ConsIntList(n, this);
    }
}
 
/**
 * Concrete empty list structure containing nothing.
 */
class EmptyIntList extends IntList {
    Object accept(IntListVisitor v) {
        return v.forEmptyIntList(this);
    }
}

/**
 * Concrete non-empty list structure containing an int, called first,
 * and a rest, which is a list structure.
 */
class ConsIntList extends IntList {
    int first;
    IntList rest;

    Object accept(IntListVisitor v) {
        return v.forConsIntList(this);
    }
}

/**
 * Abstract operation on IntList.
 */
interface IntListVisitor {
    Object forEmptyIntList(EmptyIntList host);
    Object forConsIntList(ConsIntList host);
}

Here the host structure is IntList and its concrete subclasses, and the visitor is any extrinsic operation to be performed on the IntList host. Instead of adding methods to IntList to perform additional operations, we write visitors.

*

HTML
<u>

NOTE

</u>
HTML

*: Visitors that take no arguments should be written as Singletons.
We now translate code we wrote using the interpreter pattern on IntList in previous labs using visitors instead.

...