举例如下:
package design.visitor;
/**
* 文件名称:Body.java
* 创建人:Fei Wong
* 创建时间: Jun 22, 2012
* 电子邮箱:
* */
public class Body {
public void accept(IVisitor visitor) {
visitor.visit(this);
}
}
package design.visitor;
/**
* 文件名称:Engine.java
* 创建人:Fei Wong
* 创建时间: Jun 22, 2012
* 电子邮箱
* */
public class Engine {
public void accept(IVisitor visitor) {
visitor.visit(this);
}
}
package design.visitor;
/**
* 文件名称:Wheel.java
* 创建人:Fei Wong
* 创建时间: Jun 22, 2012
* 电子邮箱:
* */
public class Wheel {
private String name;
public Wheel(String name) {
this.name = name;
}
String getName() {
return this.name;
}
public void accept(IVisitor visitor) {
visitor.visit(this);
}
}
package design.visitor;
/**
* 文件名称:Car.java
* 创建人:Fei Wong
* 创建时间: Jun 22, 2012
* 电子邮箱
* */
public 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") };
public void accept(IVisitor visitor) {
visitor.visit(this);
engine.accept(visitor);
body.accept(visitor) ;
for (int i = 0; i < wheels.length; ++ i)
wheels[i].accept(visitor);
}
}
package design.visitor;
/**
* 文件名称:Visitor.java
* 创建人:Fei Wong
* 创建时间: Jun 22, 2012
* 电子邮箱:
* */
public interface IVisitor {
void visit(Wheel wheel);
void visit(Engine engine);
void visit(Body body);
void visit(Car car);
}
package design.visitor;
public class PrintVisitor implements IVisitor {
@Override
public void visit(Wheel wheel) {
System.out.println("Visiting " + wheel.getName() + " wheel");
}
@Override
public void visit(Engine engine) {
System.out.println("Visiting engine");
}
@Override
public void visit(Body body) {
System.out.println("Visiting body");
}
@Override
public void visit(Car car) {
System.out.println("Visiting car");
}
}