Patterns / Behavioral patterns
image

import (
    "fmt"
    "strconv"
)

//Element interface
type Element interface {
    Accept(v CarVisitor)
}

//Engine is ConcreteElement
type Engine struct{}

//Accept operation that takes a visitor as an argument
func (e EngineAccept(v CarVisitor) {
    v.visitEngine(e)
}

//Wheel is ConcreteElement
type Wheel struct {
    Number int
}

//Accept operation
func (w WheelAccept(v CarVisitor) {
    v.visitWheel(w)
}

//Car is ConcreteElement
type Car struct {
    _items []Element
}

//Accept operation
func (c CarAccept(v CarVisitor) {
    for _, e := range c._items {
        e.Accept(v)
    }
    v.visitCar(c)
}

//CarVisitor is Visitor
type CarVisitor interface {
    visitEngine(engine Engine)
    visitWheel(wheel Wheel)
    visitCar(car Car)
}

//TestCarVisitor is ConcreteVisitor
type TestCarVisitor struct{}

func (v TestCarVisitorvisitEngine(engine Engine) {
    fmt.Println("test engine")
}

func (v TestCarVisitorvisitWheel(wheel Wheel) {
    fmt.Println("test wheel #" +
        strconv.Itoa(wheel.Number))
}

func (v TestCarVisitorvisitCar(car Car) {
    fmt.Println("test car")
}

//RepairCarVisitor is ConcreteVisitor
type RepairCarVisitor struct{}

func (v RepairCarVisitorvisitEngine(engine Engine) {
    fmt.Println("repair engine")
}

func (v RepairCarVisitorvisitWheel(wheel Wheel) {
    fmt.Println("repair wheel #" +
        strconv.Itoa(wheel.Number))
}

func (v RepairCarVisitorvisitCar(car Car) {
    fmt.Println("repair car")
}

//Client
car := Car{[]Element{
        Engine{},
        Wheel{1},
        Wheel{2},
        Wheel{3},
        Wheel{4},
}}
v1 := TestCarVisitor{}
v2 := RepairCarVisitor{}

car.Accept(v1)
car.Accept(v2)


Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.