访问者模式主要是将很多操作都在一个接口中声明,在接口的实现类中都要实现这些操作,
在具体的访问者类中规定了需要调用实现类的哪个方法,
例子如下:
访问者接口:
public interface Visitor {
public void visitString(StringElement stringE);
public void visitFloat(FloatElement floatE);
public void visitCollection(Collection<?> collection);
public void visitInt(IntElement inte);
}
访问者接口实现类
public class ConcreteVisitor implements Visitor{
public void visitCollection(Collection<?> collection) {
Iterator<?> iterator = collection.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
if (o instanceof Visitable) {
((Visitable)o).accept(this);
}
}
}
public void visitFloat(FloatElement floatE) {
System.out.println(floatE.getFe());
}
public void visitString(StringElement stringE) {
System.out.println(stringE.getSe());
}
@Override
public void visitInt(IntElement inte) {
System.out.println(inte.getInts());
}
}
操作类的接口:
public interface Visitable {
public void accept(Visitor visitor);
}
操作类的具体实现类:
public class FloatElement implements Visitable{
private Float fe;
public FloatElement(Float fe) {
this.fe = fe;
}
public Float getFe() {
return this.fe;
}
public void accept(Visitor visitor) {
visitor.visitFloat(this);
}
}
public class IntElement implements Visitable{
private int ints;
public int getInts() {
return ints;
}
public IntElement(int i){
this.ints = i;
}
@Override
public void accept(Visitor visitor) {
visitor.visitInt(this);
}
}
public class StringElement implements Visitable{
private String se;
public StringElement(String se) {
this.se = se;
}
public String getSe() {
return this.se;
}
public void accept(Visitor visitor) {
visitor.visitString(this);
}
}
测试类:
public class Test {
public static void main(String[] args) {
Visitor visitor = new ConcreteVisitor();
Visitable se = new StringElement("abc");
se.accept(visitor);
Visitable fe = new FloatElement(new Float(1.5));
fe.accept(visitor);
System.out.println("===========");
List<Visitable> result = new ArrayList<Visitable>();
result.add(new StringElement("abc"));
result.add(new StringElement("abc"));
result.add(new StringElement("abc"));
result.add(new FloatElement(new Float(1.5)));
result.add(new FloatElement(new Float(1.5)));
result.add(new FloatElement(new Float(1.5)));
visitor.visitCollection(result);
Visitable is = new IntElement(2);
is.accept(visitor);
}
}