美文网首页
访问者模式

访问者模式

作者: ying76 | 来源:发表于2020-02-09 13:57 被阅读0次

概述

访问者模式.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)
    }
}

相关文章

网友评论

      本文标题:访问者模式

      本文链接:https://www.haomeiwen.com/subject/udggxhtx.html