1

设计模式--访问器(Visitor)模式

 2 years ago
source link: https://segmentfault.com/a/1190000040406693
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

表示一个作用于某对象结构中的各元素的操作,使得可以在不改变(稳定)各元素的类的前提下定义(扩展)作用于这些元素的新操作(变化)

在这里插入图片描述

  • Visitor模式通过所谓双重分发(double dispatch)来实现在不更改(不添加新的操作-编译时)Element类层次结构的前提下,在运行时透明地为类层次结构上的各个类动态添加新的操作(支持变化)
  • 所谓双重分发即Visitor模式中间包括了两个多态分发:第一个为accept方法的多态辨析,第二个为visitElementX方法的多态辨析
  • Visitor模式的最大缺点在于扩展类层次结构(增加新的Element子类),会导致Visitor类的改变,因此Visitor模式适用于“Element类层次结构稳定,而其中的操作却经常面临频繁改动”

Go语言代码实现

在这里插入图片描述

visitor.go

package Visitor

import "fmt"

type IVisitor interface {
   Visit()
}

type WeiBoVisitor struct {

}

func (w WeiBoVisitor) Visit(){
   fmt.Println("Visit WeiBo")
}

type IQIYIVisitor struct {

}

func (i IQIYIVisitor) Visit () {
   fmt.Println("Visit IQiYi")
}

type IElement interface {
   Accept(visitor IVisitor)
}

type Element struct {

}

func (e Element) Accept(v IVisitor) {
   v.Visit()
}

visitor_test.go

package Visitor

import "testing"

func TestElement_Accept(t *testing.T) {
   e := new(Element)
   e.Accept(new(WeiBoVisitor))
   e.Accept(new(IQIYIVisitor))
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK