The purpose of the Visitor Pattern is to encapsulate an operation that you want to perform on the elements of a data structure (a class hierarchy which may not be necessarily related). In this way, you can change the operation being performed on a structure without the need of changing the classes of the elements that you are operating on. Using a Visitor pattern allows you to decouple the classes for the data structure and the algorithms used upon them.
The assumption is that you have received a fixed unrelated class hierarchy (from a vendor), which cannot be changed, and you need to add some new functionality to the hierarchy, which means that normally the base class interface needs to be changed. But it is not possible in our case.
In typical case we have a fixed unrelated class hierarchy whose interface cannot be changed.
A new method or behavior needs to be implemented for the fixed class hierarchy without changing the interface definition.
The design pattern that solves this kind
of problem is called a “Visitor” and it builds on the double dispatching
scheme.
Each node in the data structure "accepts" a Visitor, which sends a message to the Visitor, which includes the node's class. The visitor will then execute its algorithm for that element. This process is known as "Double Dispatching." The node makes a call to the Visitor, passing itself in, and the Visitor executes its algorithm on the node. In Double Dispatching, the call made depends upon the type of the Visitor and of the Host (data structure node), not just of one component.
The general pattern for the Visitor is as follows:

Let's look more closely at where the Double Dispatching takes place:
class ConcreteElementA extends
AElement
{
public void accept(AVisitor v)
{
v.VisitConcreteElementA(this);
}
…………………………
…………………………..
}
The key is the Accept method in the ConcreteElement classes. The body of this method shows the double dispatching call, where the Visitor is passed in to the accept method, and that visitor is told to execute its visit method, and is handed the node by the node itself. This makes for very robust code, since all of the decision making as to what to execute where and when it taken care of by the dispatching. Nobody ever needs to check anything: they just do what it is that they do, with whatever they're handed.
A code example for the Visitor pattern is in this zip file.
Composite
Interpreter
Reference:
http://exciton.cs.oberlin.edu/javaresources/DesignPatterns/VisitorPattern.htm
http://rileywhite.com/software/visitorpattern.html
Modified: 03-03-04
Yogesh Samant