The Visitor design pattern allows you to add operations to classes without changing the classes. That pretty well summarizes what the Visitor can do for you. Imagine you’ve got a great big game program and you want to tweak the functionality of certain objects in the game by adding operations (methods and functions). Rather than opening a bag of marbles to spill out in every direction when you add functionality to a class, all you need to do is to use the Visitor to add that functionality without interfering with the rest of the class. If you’ve read Chandima’s chapter and posts on the Composite pattern, you’re two jumps ahead. Typically, the Visitor is used with a Composite pattern. Likewise, Chandima’s post on the Iterator will aid in understanding the traverse process used in the Visitor. Of course you can work perfectly well with the Visitor without background in these other patterns, but you might want to peek at them for further reference and understanding as you review the Visitor.
The Visitor Design Pattern’s Formal Features
First, take a look at the Visitor’s class diagram. You will note that the implied Client holds references to two different classes within the pattern. The factory patterns (Abstract Factory, Factory, Flyweight) all have similar multiple references from the Client, and so too does the Command, Interpreter and Iterator patterns. So don’t let the multiple references from the Client throw you. Figure 1 shows the Visitor class diagram:

Figure 1:Visitor design pattern diagram
The Client reference to the Visitor interface (IVisitor in the example program) sets up implementations for concrete visitors. The concrete visitors visit the different concrete elements. At the same time, the client goes through the ObjectStructure and the ObjectStructure has multiple object references to the Element interface. The black ball at the end of the ObjectStructure reference arrow means that it has multiple references. Figure 2 isolates that relationship from the Visitor diagram.

Figure 2: Multiple object references
Getting the ObjectStructure and its references to the Element class is an important part of working successfully with the Visitor pattern.
Double-Dispatch
One of the key processes behind the Visitor’s ability to add operations to existing classes is the double-dispatch technique. Like the name implies, double-dispatch involves two receivers. A single-dispatch involves the name of the request and the type of receiver. In double-dispatch the executed operation depends on the kind of request and two receivers. In the Visitor example program, you will see that the accept method is a double dispatch operation. Within a concrete element, it is written as:
public function accept(visitor:IVisitor):void
{
visitor.visitConcreteElementA(this);
}
The this statement refers to the Concrete Element class it is contained within. In this context you can see the visitor and element receivers that make it a double-dispatch operation. The actual operation that is executed depends on the type of Visitor and Element. Using this technique allows you to consolidate the operation in the Visitor.
In order to make the double-dispatch more visible in an example, the program uses an unsigned color value distributed between the Visitor and Element. The generated value is displayed as a string representing an unsigned integer.(e.g., 0×00aa04). The Element contains the first six characters (e.g., 0xff00) and the Visitor provides the last two characters (e.g.. ff). The operation in the Element expects a parameter containing the last two characters, and when the operation is launched from a concrete Visitor, it supplies the required characters. The combined string is displayed in a trace statement and also converted into an unsigned integer (just to keep me honest!).
Traverse the Elements
The procedure whereby the visitor visits all of the elements is the traverse process. Gamma et al suggest using the object structure, an iterator or add a traversal algorithm in the visitor. Of these methods for traversing the elements I selected the object structure because it’s the clearest to easiest to get started with. Included in the object structure (class ObjectStructure) is an array of the elements and a loop iterates through the array where the array elements are pushed onto the array. A second operation (the accept method) goes through the elements and accepts the visitor.
The Visitor Interface and Concrete Classes
The minimalist example is designed to illustrate the structure of the Visitor design pattern. To that end, trace statements show where the visitor visits and show how the different combinations of visitor and visited can be used to generate unsigned integer values typically used for assigning values to colors.
First , I used an interface instead of abstract classes for both the visitor and element classes. You might want to consider using abstract classes for the element interface, especially if you want to add a bit more detail to the operations. However, for this example, the interface is sufficient. The visitor participants are listed in the following scripts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | //Visitor Interface package { public interface IVisitor { function visitConcreteElementA(concreteElementA:ConcreteElementA):void; function visitConcreteElementB(concreteElementB:ConcreteElementB):void; } } //Concrete Visitor 1 package { public class ConcreteVisitor1 implements IVisitor { private var visNow:String = String(this); public function visitConcreteElementA(concreteElementA:ConcreteElementA):void { visNow = String(this); trace(visNow.slice(visNow.indexOf("C"),visNow.length - 1) + " visits Concrete Element A"); concreteElementA.operationA("ff"); } public function visitConcreteElementB(concreteElementB:ConcreteElementB):void { visNow = String(this); trace(visNow.slice(visNow.indexOf("C"),visNow.length - 1) + " visits Concrete Element B"); concreteElementB.operationB("ff"); } } } //Concrete Visitor 2 package { public class ConcreteVisitor2 implements IVisitor { private var visNow:String = String(this); public function visitConcreteElementA(concreteElementA:ConcreteElementA):void { visNow = String(this); trace(visNow.slice(visNow.indexOf("C"),visNow.length - 1) + " visits Concrete Element A"); concreteElementA.operationA("00"); } public function visitConcreteElementB(concreteElementB:ConcreteElementB):void { visNow = String(this); trace(visNow.slice(visNow.indexOf("C"),visNow.length - 1) + " visits Concrete Element B"); concreteElementB.operationB("00"); } } } |
Each of the concrete visitor classes has methods for visiting the two elements that make up the program. The trace statement does a little fancy footwork to extract the name of the class from the this statement, but all it is really doing is to show that the visitor is visiting each of the concrete elements in the program. Each of the visit operations also calls the element operations and passes values to them. The first visitor passes “ff” and the second passes “00.” When combined with the elements, four unique values are generated.
The Element Interface and Classes
As noted above the interface structure is used with the element classes. I tested it with an abstract class, and it worked just as well, but unless I need to use an abstract class, I prefer the interface.
The element interface (IElement) establishes the accept( visitor:IVisitor) method. Each of the two element classes include an accept() method (required by the interface) as well as a generic operation and a getState() method. The generic operation is set up to accept a string parameter and display a color value string (e.g.,0xaa22d7) based on the parameter value from the visitor and the current state provided by the getState() method. (The current state is set up as a literal for illustrative purposes.)
The Freemans (authors of Head First Design Patterns) point out that the visitors need to get the state of the elements and that each element should have a getState() method. So I just created a getState() private function and then tucked it in the trace statement as a value that is displayed when the visitor invokes the operation and passes a value for the operation’s parameter. In this way, the design implies a far more dynamic system.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | //Element Interface package { public interface IElement { function accept( visitor:IVisitor):void; } } //Concrete Element 1 package { public class ConcreteElementA implements IElement { private var currentState:String; public function accept(visitor:IVisitor):void { visitor.visitConcreteElementA(this); } public function operationA(color:String):void { trace(getState()+color +"\n"); //Convert into actual number var clr:uint=uint(getState()+color); } private function getState():String { currentState="0xff00"; return currentState; } } } //Concrete Element 2 package { public class ConcreteElementB implements IElement { private var currentState:String; public function accept(visitor:IVisitor):void { visitor.visitConcreteElementB(this); } public function operationB(color:String):void { trace(getState()+color +"\n"); //Convert into actual number var clr:uint = uint(getState() + color); } private function getState():String { currentState = "0x00ff"; return currentState; } } } |
The final part is to set up a class where we can organize the structure providing a doorway for the client.
The Object Structure and Client
As noted above, the ObjectStructure participant in the Visitor design pattern is where an operation is set up so that the visitor traverses the different concrete elements. The class has no constructor, but instead serves as a set of operations providing traverse services for the client to use for making calls to the Visitor.
As seen in the diagram structure, the ObjectStructure holds multiple references to the element classes in the attach() operation. The accept() function represents the double-dispatch technique so critical to the Visitor pattern.
Once the ObjectStructure class is set up, the Client class can use its operations to send requests to the Element side of the Visitor. However, as you remember, the Client also holds a reference to the Visitor classes, and so you will see both instances and references to the Visitor classes and the Element classes. The references to the visitor side is direct, but the references to the elements are through the object structure via the attach() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | //Object Structure package { public class ObjectStructure { private var elements:Array=[]; public function attach(element:IElement ):void { elements.push(element); } public function accept( visitor:IVisitor):void { for each (var e:IElement in elements) { e.accept(visitor); } } } } //Client package { import flash.display.Sprite; //Client public class Client extends Sprite { private var snoopy1:IVisitor; private var snoopy2:IVisitor; private var obStru:ObjectStructure; public function Client() { setUp(); } private function setUp():void { //Setup obStru = new ObjectStructure; obStru.attach(new ConcreteElementA()); obStru.attach(new ConcreteElementB()); // Create visitors snoopy1 = new ConcreteVisitor1(); snoopy2 = new ConcreteVisitor2(); // Accept visitors obStru.accept(snoopy1); obStru.accept(snoopy2); } } } |
When you test the program in either Flex or Flash, you get the following output:
ConcreteVisitor1 visits Concrete Element A
0xff00ff
ConcreteVisitor1 visits Concrete Element B
0×00ffff
ConcreteVisitor2 visits Concrete Element A
0xff0000
ConcreteVisitor2 visits Concrete Element B
0×00ff00
As you can see, the element states work out to different “color” values depending on what the visitor brings to the plate. Being a bare bones minimalist example, you should be able to see all of the parts and how they interact. You can also add a “detach” operation so that you can pick and choose which visitors visit which elements.

The ActionScript 3.0 Visitor Design Pattern: A Tale of Traverser and the Double-Dispatch Kid by William B. Sanders, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.
Related posts:

Bill Sanders
Nice blog post. I am wondering why you wouldn’t use the decorator pattern for this instead?
Hi Eamonn,
You may well be able to do the same thing with the Decorator,but what we’re trying to do is to provide a complete set of Design Patterns in ActionScript 3.0 between this blog and our book. (We’ve almost completed them all!)
In going over Chapter 4, I can see your point. The Decorator does indeed provide functionality to the component classes. The quick answer lies in the role of double-dispatch versus wrapping. The Visitor uses double-dispatch and the Decorator uses wrapping. However, let me look at both of them more closely and see if I can provide a better answer. (You can do the same! We’re a very democratic blog!)
Kindest regards,
Bill
Well, correct me if I’m wrong here, but at least in this example, it seems that the difference between the decorator and visitor patterns has to do with a method/property distinction. In the decorator you are adding to the method, whereas in this visitor example, it is the properties or parameters that affect the change. So with the visitor it is a case of how you use the methods (different visitors use the exact same methods differently), whereas with the decorator it is a case of what the methods do (different decorations will apply different overall functionality to the method).
Hi Regard,
Perhaps the most useful way to distinguish between the Visitor and Decorator patterns is to begin with their general purposes and the aspects of the designs that can vary. The Decorator is a Structural pattern that can change the responsibilities of an object without subclassing. The Visitor is a Behavioral pattern that varies the operations that can be applied to objects without changing their classes. Structural object patterns describe ways to compose objects to realize new functionality instead of composing interfaces or implementations. The Decorator realizes the new functionality by wrapping objects with the functionality. The Visitor, on the other hand, encapsulates behavior that would otherwise be distributed across classes. As a Behavioral pattern, the Visitor focuses on algorithms and the assignment of responsibilities between objects. The big difference is that Behavioral object patterns (like the Visitor) use object composition rather than inheritance. But in looking at the Decorator, you see how it makes use of inheritance to compose interfaces and/or implementations.
In distinguishing between any design patterns, I always start with the larger categories (such as type) and look at the elements that vary. It’s an easy way to distinguish both the purpose and the approach to problem solving.
Kindest regards,
Bill
have you come across, or considered the multi-method pattern?
http://nice.sourceforge.net/visitor.html
??
or maybe I have read it wrong.
multimethods isn’t a pattern, but a concept available in some languages, and the visitor is a pattern aimed at giving “multiple dispatch in a language that lacks it”
Hi Neil,
I see you’re using Java (no?) and a language called ‘Nice,’ and while we welcome insights and information from developers using other languages, the focus of our discussion is ActionScript 3.0 and Design Patterns using Adobe Flex Builder and Flash.
From a quick look at Nice, I cannot tell whether the role of multiple dispatch that apparently is built into Nice accomplishes exactly the same thing as the Visitor design pattern. While double dispatch is part of the Visitor, the key purpose of the Visitor is to add functionality (operations/methods/functionality) to components without changing the components–components in this case being any concrete class that makes up an element of a program.
In any case, thanks for your “Visit” to our blog.
Kindest regards,
Bill
thanks for the response, I’m actually an AS3 Developer, and was looking for a solution for a problem which I thought the visitor might solve. I came across that link, and mistook “multimethods” as a pattern, instead of multiple despatching.
Any how I used a reworked implementation of the visitor to create channels of communication between a stack of loosely coupled pureMVC proxies, and it worked a treat.
If I get a chance to write it up, I’ll ping you back.
cheers, thanks for the resource, very hard to find AS3 implementations for many patterns
Hi Neil,
Glad to hear that you found (or created) a solution. I would be very interested in seeing your re-worked Visitor, and Chandima is always interested in PureMVC.
So definitely ping back when you get a chance to write it up.
Kindest regards,
Bill