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.
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.
Thanks Buddy for explaining Visitor design pattern in Plain English !
RSS feed for comments on this post · TrackBack URI
You must be logged in to post a comment.
Johnna said,
September 22, 2007 @ 8:03 pmVisitor design pattern is used in compiler for grammar checking and word processors for spelling check