Visitor Design Pattern

How The Visitor Pattern Works - Peter Rose

A Visitor is like a plumber who is called to a house to fix something. The house is “visitable”, i.e. it allows Visitors to enter. However, it doesn’t know how to fix the plumbing, so it calls a plumber. The plumber, however, doesn’t know anything about the house. It only knows about plumbing. The house knows about itself, so when the Visitor comes in the house, the house doesn’t even know whether the Visitor is a plumber or electrician or painter. But it does know that it has rooms.


So, when a Visitor enters the house (programatically through the house’s accept(Visitor visitor) method), it allows the Visitor to look at it first. It then shows (i.e. passes) the Visitor to each room in the house (through each room’s own accept(Visitor visitor) method). When the Visitor enters a room (as it did when it entered the house itself), it knows if that room has plumbing or not. If no plumbing is in the room, the Visitor does nothing; if there is plumbing, then the Visitor does what it is programmed to do.

Interestingly, the way the Visitor checks each room to see if it is interested in it is to have the room pass itself into the Visitor’s visit() method (i.e. visitor.visit(this)). The Visitor thus has access to the internals of that room/object. This is how it determines if it has any work to do with that particular object.

This process of the Visitor being passed in through the Visitable object’s accept() method and then the Visitable object being passed into the Visitor through its visit() method is called “double dispatch”.

Most examples of the Visitor Pattern show traversing through data structures such as linked lists, however, as application programmers we tend not to deal with raw data structures as much as we do collections of objects in inheritance and aggregation relationships.

Johnna said,

September 22, 2007 @ 8:03 pm

Visitor design pattern is used in compiler for grammar checking and word processors for spelling check

John James said,

September 23, 2007 @ 11:30 pm

Thanks Buddy for explaining Visitor design pattern in Plain English !

RSS feed for comments on this post · TrackBack URI