The basic idea is that you have a set of element classes that form an object structure. Each of these element classes has an accept method that takes a Visitor object as an argument. The Visitor is an interface that has a different visit method for each element class. The accept method of an element class calls back the visit method for its class. Separate concrete Visitor classes can then be written that perform some particular operations.
class Wheel{
private String name;
Wheel(String name){
this.name = name;
}
String getName(){
return this.name;
}
void accept(Visitor visitor){
visitor.visit(this);
}
}
class Engine{
void accept(Visitor visitor){
visitor.visit(this);
}
}
class Body{
void accept(Visitor visitor){
visitor.visit(this);
}
}
public class VisitorDemo{
static public void main(String[] args){
Car car = new Car();
Visitor visitor = new PrintVisitor();
car.accept(visitor);
}
}
Python Example
class Wheel:
def __init__(self,name):
self.name = name
def accept(self,visitor):
visitor.visitWheel(self)
class Engine:
def accept(self,visitor):
visitor.visitEngine(self)
class Body:
def accept(self,visitor):
visitor.visitBody(self)
class Car:
def __init__(self):
self.engine = Engine()
self.body = Body()
self.wheels = [ Wheel("front left"), Wheel("front right"),
Wheel("back left") , Wheel("back right") ]
def accept(self,visitor):
visitor.visitCar(self)
self.engine.accept( visitor )
self.body.accept( visitor )
for wheel in self.wheels:
wheel.accept( visitor )
class PrintVisitor:
def visitWheel(self,wheel):
print "Visiting "+wheel.name+" wheel"
def visitEngine(self,engine):
print "Visiting engine"
def visitBody(self,body):
print "Visiting body"
def visitCar(self,car):
print "Visiting car"
car = Car()
visitor = PrintVisitor()
car.accept(visitor)
Java Example
interface Visitor{
void visit(Wheel wheel);
void visit(Engine engine);
void visit(Body body);
void visit(Car car);
}
class Car{
private Engine engine = new Engine();
private Body body = new Body();
private Wheel[] wheels
= { new Wheel("front left"), new Wheel("front right"),
new Wheel("back left") , new Wheel("back right") };
void accept(Visitor visitor){
visitor.visit(this);
engine.accept( visitor );
body.accept( visitor );
for(int i=0; i
See also: design pattern, Composite pattern, Hierarchical visitor pattern