访问者模式

ying76 · · 1197 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

概述

访问者模式.jpg

Golang实现

target.go

type Target interface {
    Accept(Visitor)
}

visitor.go

type Visitor interface {
    VisitBuilding(building Building)
    VisitApartment(apartment Apartment)
}

apartment.go

type Apartment struct {
   Name string
}

func (a Apartment) Accept(v Visitor) {
   v.VisitApartment(a)
}

building.go

type Building struct {
    Apartments list.List
}

func (b Building) Accept(v Visitor) {
    v.VisitBuilding(b)
}

cleaner.go

type Cleaner struct {}

func (c Cleaner) VisitApartment(a Apartment) {
    fmt.Printf("cleanup Apartment %s\n", a.Name)
}

func (c Cleaner) VisitBuilding(b Building) {
    for e := b.Apartments.Front(); e != nil; e = e.Next() {
        c.VisitApartment(e.Value.(Apartment))
    }
}

viruskiller.go

type VirusKiller struct {}

func (vk VirusKiller) VisitApartment(a Apartment) {
    fmt.Printf("Kill virus for Apartment %s\n", a.Name)
}

func (vk VirusKiller) VisitBuilding(b Building) {
    for e := b.Apartments.Front(); e != nil; e = e.Next() {
        vk.VisitApartment(e.Value.(Apartment))
    }
}

visit.go

func main() {
    list:= list.List{}
    list.PushBack(visitor.Apartment{Name:"B101"})
    list.PushBack(visitor.Apartment{Name:"B102"})
    list.PushBack(visitor.Apartment{Name:"B103"})

    targets := []visitor.Target{
        visitor.Apartment{Name:"101"},
        visitor.Apartment{Name:"103"},
        visitor.Building{Apartments: list},
        visitor.Apartment{Name:"201"},
    }

    c := visitor.Cleaner{}
    k := visitor.VirusKiller{}
    for _, item := range targets {
        item.Accept(c)
    }
    for _, item := range targets {
        item.Accept(k)
    }
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:ying76

查看原文:访问者模式

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1197 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传