81 lines
1.4 KiB
Go
81 lines
1.4 KiB
Go
package main
|
|
|
|
import "fmt"
|
|
|
|
/*
|
|
实例:
|
|
汤宝宝坚信搭积木是人类的未来,因此开办了一家积木厂。
|
|
*/
|
|
|
|
// 抽象Node接口 Shape
|
|
type Shape interface {
|
|
Accept(visitor Visitor)
|
|
ClaimShape()
|
|
}
|
|
|
|
type Circle struct{}
|
|
|
|
func (c *Circle) Accept(visitor Visitor) {
|
|
visitor.VisitCircle(c)
|
|
}
|
|
|
|
func (c *Circle) ClaimShape() {
|
|
fmt.Println("I am a Circle")
|
|
}
|
|
|
|
type Square struct{}
|
|
|
|
func (s *Square) Accept(visitor Visitor) {
|
|
visitor.VisitSquare(s)
|
|
}
|
|
|
|
func (s *Square) ClaimShape() {
|
|
fmt.Println("I am a Square")
|
|
}
|
|
|
|
type Triangle struct{}
|
|
|
|
func (t *Triangle) Accept(visitor Visitor) {
|
|
visitor.VisitTriangle(t)
|
|
}
|
|
|
|
func (t *Triangle) ClaimShape() {
|
|
fmt.Println("I am a Triangle")
|
|
}
|
|
|
|
// 抽象NodeVisitor接口 Visitor
|
|
type Visitor interface {
|
|
VisitCircle(c *Circle)
|
|
VisitSquare(s *Square)
|
|
VisitTriangle(t *Triangle)
|
|
}
|
|
|
|
type ShapeVisitor struct{}
|
|
|
|
func (sv *ShapeVisitor) VisitCircle(c *Circle) {
|
|
fmt.Print("Visiting Circle: ")
|
|
c.ClaimShape()
|
|
}
|
|
|
|
func (sv *ShapeVisitor) VisitSquare(s *Square) {
|
|
fmt.Print("Visiting Square: ")
|
|
s.ClaimShape()
|
|
}
|
|
|
|
func (sv *ShapeVisitor) VisitTriangle(t *Triangle) {
|
|
fmt.Print("Visiting Triangle: ")
|
|
t.ClaimShape()
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println("========== 访问者模式 ==========")
|
|
shapes := []Shape{&Circle{}, &Square{}, &Triangle{}}
|
|
visitor := &ShapeVisitor{}
|
|
|
|
for _, shape := range shapes {
|
|
shape.Accept(visitor)
|
|
}
|
|
fmt.Println()
|
|
fmt.Println("======== 访问者模式结束 ========")
|
|
}
|