访问者模式是一种行为设计模式, 它能将算法与其所作用的对象隔离开来。
如果你需要对一个复杂对象结构(例如对象树)中的所有元素执行某些操作,可使用访问者模式。
可使用访问者模式来清理辅助行为的业务逻辑。
当某个行为仅在类层次结构中的一些类中有意义,而在其他类中没有意义时,可使用该模式。
shape.go: 元件
package main
type Shape interface {
getType() string
accept(Visitor)
}
square.go: 具体元件
package main
type Square struct {
side int
}
func (s *Square) accept(v Visitor) {
v.visitForSquare(s)
}
func (s *Square) getType() string {
return "Square"
}
circle.go: 具体元件
package main
type Circle struct {
radius int
}
func (c *Circle) accept(v Visitor) {
v.visitForCircle(c)
}
func (c *Circle) getType() string {
return "Circle"
}
rectangle.go: 具体元件
package main
type Rectangle struct {
l int
b int
}
func (t *Rectangle) accept(v Visitor) {
v.visitForrectangle(t)
}
func (t *Rectangle) getType() string {
return "rectangle"
}
visitor.go: 访问者
package main
type Visitor interface {
visitForSquare(*Square)
visitForCircle(*Circle)
visitForRectangle(*Rectangle)
}
areaCalculator.go: 具体访问者
package main
import (
"fmt"
)
type AreaCalculator struct {
area int
}
func (a *AreaCalculator) visitForSquare(s *Square) {
// Calculate area for square.
// Then assign in to the area instance variable.
fmt.Println("Calculating area for square")
}
func (a *AreaCalculator) visitForCircle(s *Circle) {
fmt.Println("Calculating area for circle")
}
func (a *AreaCalculator) visitForRectangle(s *Rectangle) {
fmt.Println("Calculating area for rectangle")
}
middleCoordinates.go: 具体访问者
package main
import "fmt"
type MiddleCoordinates struct {
x int
y int
}
func (a *MiddleCoordinates) visitForSquare(s *Square) {
// Calculate middle point coordinates for square.
// Then assign in to the x and y instance variable.
fmt.Println("Calculating middle point coordinates for square")
}
func (a *MiddleCoordinates) visitForCircle(c *Circle) {
fmt.Println("Calculating middle point coordinates for circle")
}
func (a *MiddleCoordinates) visitForRectangle(t *Rectangle) {
fmt.Println("Calculating middle point coordinates for rectangle")
}
main.go: 客户端代码
package main
import "fmt"
func main() {
square := &Square{
side: 2}
circle := &Circle{
radius: 3}
rectangle := &Rectangle{
l: 2, b: 3}
areaCalculator := &AreaCalculator{
}
square.accept(areaCalculator)
circle.accept(areaCalculator)
rectangle.accept(areaCalculator)
fmt.Println()
middleCoordinates := &MiddleCoordinates{
}
square.accept(middleCoordinates)
circle.accept(middleCoordinates)
rectangle.accept(middleCoordinates)
}
output:
Calculating area for square
Calculating area for circle
Calculating area for rectangle
Calculating middle point coordinates for square
Calculating middle point coordinates for circle
Calculating middle point coordinates for rectangle
更多【golang-[go] 访问者模式】相关视频教程:www.yxfzedu.com