Skip to content
← 返回设计模式列表
设计意图与对象责任

访问者 ​

在对象结构外添加一组操作。

行为型

说明 ​

元素类型稳定、操作经常增加时适用;新增元素类型需修改所有访问者。

分析 ​

Element 把自己交给 Visitor 的对应方法,访问者据此对不同元素执行不同操作。新增一种操作只需增加访问者实现,例如描述、导出或统计。

Accept 将具体元素传回访问者对应的方法:Text 进入 VisitText,Image 进入 VisitImage。这让新增导出操作集中在一个访问者内;反过来新增 Video 元素时,Visitor 接口及所有实现都要改变。示例仅展示单个元素分派,遍历文档树的责任还需由容器或调用方明确承担。

查看图表代码

适用前提与边界 ​

新增元素类型却要求所有访问者增加方法,因此它适合元素种类相对稳定的结构。 交互流程很短且稳定时,直接调用通常更容易理解。

示例输入与调用 ​

go
var element Element = Text{Value: "hello"}
	fmt.Println(element.Accept(Describe{}))

运行输出 ​

text
text: hello

完整 Go 示例 ​

go
package main

import "fmt"

type Visitor interface {
	VisitText(Text) string
	VisitImage(Image) string
}
type Element interface{ Accept(Visitor) string }
type Text struct{ Value string }
type Image struct{ URL string }

func (t Text) Accept(v Visitor) string {
	return v.VisitText(t)
}
func (i Image) Accept(v Visitor) string {
	return v.VisitImage(i)
}

type Describe struct{}

func (Describe) VisitText(t Text) string {
	return "text: " + t.Value
}
func (Describe) VisitImage(i Image) string {
	return "image: " + i.URL
}

func main() {
	var element Element = Text{Value: "hello"}
	fmt.Println(element.Accept(Describe{}))
}

继续阅读