概述
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)
}
}
有疑问加站长微信联系(非本文作者)