Visitor pattern 经常被 compiler 的 parser 使用,比如 Eclipse JDT AST Parser.
它基本包含两个重要的接口, Visitor 和 Element
Visitor 模式举例
设想一个旅游者首次访问 New York, 而New York也接受它的访问。一旦访问开始,将自动访问New York的景点,他不需要调用访问 museum 的函数,此方式是整个一套打包。
Visitor 模式类图
Visitor 模式的步骤
工作流程如下:
1. visitor FirstTimeVisitor 和元素 City 被建立
2. 程序以 “City accept a visitor”.为开始
3. City 定义的accept 方法接受 visitor 去访问.
4. 被接受的 visitor 用他定义的重载(overloaded)方法“visit” 来访问 City.
Java 代码如下
-
import java.util.ArrayList;
-
-
interface Visitor {
-
public void visit(City city);
-
public void visit(Museum museum);
-
public void visit(Park park);
-
}
-
-
class FirstTimeVisitor implements Visitor {
-
-
@Override
-
public void visit(City city) {
-
System.out.println("I'm visiting the city!");
-
}
-
-
@Override
-
public void visit(Museum museum) {
-
System.out.println("I'm visiting the Museum!");
-
}
-
-
@Override
-
public void visit(Park park) {
-
System.out.println("I'm visiting the Park!");
-
}
-
}
-
-
interface Element {
-
public void accept(Visitor visitor);
-
}
-
-
class City implements Element {
-
-
ArrayList<Element> places = new ArrayList<Element>();
-
-
public City() {
-
places.add(new Museum());
-
places.add(new Park());
-
}
-
-
@Override
-
public void accept(Visitor visitor) {
-
System.out.println("City is accepting visitor.");
-
visitor.visit(this);
-
-
for (Element e : places) {
-
e.accept(visitor);
-
}
-
}
-
}
-
-
class Museum implements Element {
-
@Override
-
public void accept(Visitor visitor) {
-
System.out.println("Museum is accepting visitor.");
-
visitor.visit(this);
-
}
-
}
-
-
class Park implements Element {
-
@Override
-
public void accept(Visitor visitor) {
-
System.out.println("Park is accepting visitor.");
-
visitor.visit(this);
-
}
-
-
}
-
-
public class TestVisitor {
-
public static void main(String[] args) {
-
FirstTimeVisitor visitor = new FirstTimeVisitor();
-
City city = new City();
-
city.accept(visitor);
-
}
-
}
输出
City is accepting visitor.
I’m visiting the city!
Museum is accepting visitor.
I’m visiting the Museum!
Park is accepting visitor.
I’m visiting the Park!
JDK中的 Visitor 模式
javax.lang.model.element.AnnotationValue 明显使用了 Visitor pattern, 但它很少被正规项目使用
转自:http://blog.csdn.net/span76/article/details/18363405
阅读(1264) | 评论(0) | 转发(0) |