---
title: "Design Patterns -- Visitor"
author: "dr2tr"
date: "2007-03-13T17:10:00Z"
tags: []
slug: "design-patterns-visitor"
draft: false
lastmod: "2007-03-13T17:10:00Z"
id: 233428
url: "https://dr2tr.iteye.com/blog/233428"
---

Visitor 模式是这个系列文章（也是笔者在读的这本书）的最后一个模式。按惯例，首先给出定义：Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

总结一下，这里有两点：1。添加operation 2。不改变原有的classes

事实上，到后面我们会发现要实现上面的两点有一个前提，就是原有的classes里必须有一个传入visitor 的函数。（即在开始设计类时，必须为后面的扩展留出一个冗余的函数。当然，这个函数也可以在子类里再添加。）

看一下类图：

 ![](http://www.dofactory.com/Patterns/Diagrams/visitor.gif)

这张图比较大，从Client 到ObjectStruture 到Element, 我们可以把这三者合起来作为一个已存在的Hierarchy(classes)。然后就可以看到，在加入Visitor 后，通过Accept 方法的调用，使Visitor 得以进入到Element 内部，接收Element（即，将Element 自身的控制权交给Visitor，比如通过：vistor.VisitConcreteElementB(this)）

而《Design Pattern Java Workbook》认为，要较好的运用Visitor 模式，一般需要两点：

1。已有的classes （如Element ）使其属性可访问(public )。

2。在Element 内部添加类似Accept 的函数并定义Visitor 。

另外，说到Visitor 模式，不可避免的要说一下 "double dispatch".  假设在Vistor 中有方法accept ( visitorInterface), Client 中有方法visit ( clientInterface). （请注意，这里说visitorInterface 和clientInterface, 意味着继承他们的各有不同的Visitor 和Client. ）如图：

。。。（图没法传）

该顺序图大意为：首先Visitor 调用Client 的Accept ( this); 接着Client 的Accept 方法中调用传入Visitor 的 visit (this)。通过着简单的两步，保证了动态调用的 Visitor 是本Client 对应的Vistor。

“double dispatch“ 是Vistor 中比较重要的一点。另外，当Visitor 需要访问的Hierarchy 是一个比较复杂的结构（比如Composite）时，情况也需要更详细的处理。

这里只是简单介绍一些基本的东西，所以上述的内容不做描述，如果有读者有兴趣可以参考给出的参考文献。

 

参考：

[http://www.dofactory.com/Patterns/PatternVisitor.aspx](http://www.dofactory.com/Patterns/PatternVisitor.aspx)

[http://www.crackj2ee.com/Article/ShowArticle.asp?ArticleID=227](http://www.crackj2ee.com/Article/ShowArticle.asp?ArticleID=227)（笔者认为此文内容有误，仅供参考）

[http://www.cs.rice.edu/~cork/Book/node62.html](http://www.cs.rice.edu/~cork/Book/node62.html)

[http://www.cnblogs.com/zhenyulu/articles/79719.html](http://www.cnblogs.com/zhenyulu/articles/79719.html)

[http://www.cjsdn.net/post/view?bid=17&id=180748&sty=3&age=0](http://www.cjsdn.net/post/view?bid=17&amp%3Bid=180748&amp%3Bsty=3&amp%3Bage=0) 

[http://www.cnblogs.com/idior/archive/2006/02/03/325036.html](http://www.cnblogs.com/idior/archive/2006/02/03/325036.html)