Java:
interface Visitor {
void visit(Wheel wheel);
void visit(Engine engine);
void visit(Body body);
void visit(Car car);
}
interface Visitable {
public void accept(Visitor visitor);
}
class Wheel implements Visitable {
private String name;
Wheel(String name) {
this.name = name;
}
String getName() {
return this.name;
}
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class Engine implements Visitable{
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class Body implements Visitable{
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class Car implements Visitable {
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") };
public Engine getEngine() {
return this.engine;
}
public Body getBody() {
return this.body;
}
public Wheel[] getWheels() {
return this.wheels;
}
public void accept(Visitor visitor) {
visitor.visit(this);
engine.accept(visitor);
body.accept(visitor);
for(int i = 0; i < wheels.length; ++i) {
wheels[i].accept(visitor);
}
}
}
class PrintVisitor implements Visitor {
public void visit(Wheel wheel) {
System.out.println("Visiting "+ wheel.getName()
+ " wheel");
}
public void visit(Engine engine) {
System.out.println("Visiting engine");
}
public void visit(Body body) {
System.out.println("Visiting body");
}
public void visit(Car car) {
System.out.println("Visiting car");
}
}
public class VisitorDemo {
static public void main(String[] args){
Car car = new Car();
Visitor visitor = new PrintVisitor();
car.accept(visitor);
}
}
I guess I don't get this one — if you're able to modify the object structure enough to add »accept«-methods to your objects, why do you need a visitor? Or is it just a functor implementation? If so, you could do something like:
(define do-stuff-to-the-car for-each) (define car (list "front left wheel" "front back wheel" "engine")) (define visit (cut print "visited " <>)) (define destroy (cut destroy "destroyed " <>)) (do-stuff-to-the-car print car) (do-stuff-to-the-car destroy car)