实现访问者模式示例,添加形状、访问者及具体实现,增强代码可读性
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
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("======== 访问者模式结束 ========")
|
||||
}
|
||||
Reference in New Issue
Block a user