Rice University - Comp 212 - Intermediate Programming

Fall 2001

Lecture #09 - Decoupling Data Structures from Algorithms - The Visitor Pattern


I. Functional List Structure

Recall the functional Scheme-like list data structure, AList.

list.png (9749 bytes)

Each time we want to compute something new, we have to edit each class and add appropriate methods to each class.  Is there a way to add new behavior to AList (and its variants) without touching any of the existing code, leaving everything that has been written so far unchanged?


II. Functional List Framework

The key is to encapsulate the variant behaviors into a separate union pattern.  Here, the variant behaviors are the infinitely many algorithms (i.e. computations) that we want to operate on  AList .  The invariant behaviors are the methods getFirst () and getRest ().  For AList to execute any of these algorithms, we just need to add to the design of AList one more method and never have to modify anything ever again!

This is an example of what is called the Visitor Pattern.  Class AListFW is calle the host and its method execute () is called a "hook" to the IListAlgo visitors.  Via polymorphism, AListFW knows exactly what method to call on the specific IListAlgo visitor.  As such, AListFW is said to be a framework for reusing and extending the list structure.  It is capable of executing any algorithm, past, present, and future, that conforms to the IListAlgo interface.  IListAlgo is said to define a protocol for communication between a list and algorithms on a list.

III. The Visitor Pattern

The visitor pattern is a framework for communication and collaboration between two union patterns: a "host" union and a "visitor" union.  An abstract visitor is usually defined as an interface 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!

hostVisitors.png (14027 bytes)

All the "state-less" visitors should be singletons.

 

dxnguyen@cs.rice.edu
Copyright 2001, Dung X. Nguyen - All rights reserved.