import java.util.ArrayList;
import java.util.List;
/**
* 访问者模式
*/
public class Main {
public static void main(String[] args) {
Visitor visitor = new ConcreteVisitor();
List result = new ArrayList();
result.add(new StringElement("a"));
result.add(new StringElement("b"));
result.add(new StringElement("c"));
result.add(new FloatElement(new Float(1)));
result.add(new FloatElement(new Float(2)));
result.add(new FloatElement(new Float(3)));
visitor.visitCollection(result);
}
}
import java.util.Collection;
public interface Visitor {
public void visitString(StringElement stringE);
public void visitFloat(FloatElement floatE);
public void visitCollection(Collection collection);
}
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());
}
}
public interface Visitable {
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 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);
}
}
用法:
访问者设计模式比较不好理解,首先针对的业务是遍历和访问一个元素,其次如何遍历和访问的策略通过参数传进去,如果想换一种访问方式,只要修改访问策略就可以,这又是一个策略模式的特殊应用,策略指的是遍历和访问的策略。