Golang设计模式之访问者模式

Jackey Golang 42 次浏览 , , 没有评论

创建文件Base.go

package visitor

type Customer interface { // 接待者
    Accept(Visitor)
}

type Visitor interface { // 访问者
    Visit(Customer)
}

创建文件EnterpriseCustomer.go

package visitor

type EnterpriseCustomer struct {
    name string
}

func NewEnterpriseCustomer(name string) *EnterpriseCustomer {
    return &EnterpriseCustomer{name: name}
}

func (e *EnterpriseCustomer) Accept(visitor Visitor) {
    visitor.Visit(e)
}

创建文件IndividualCustomer.go

package visitor

type IndividualCustomer struct {
    name string
}

func NewIndividualCustomer(name string) *IndividualCustomer {
    return &IndividualCustomer{name: name}
}

func (e *IndividualCustomer) Accept(visitor Visitor) {
    visitor.Visit(e)
}

创建文件CustomerCol.go

package visitor

type CustomerCol struct {
    customers []Customer // 接待着集合
}

func (c *CustomerCol) Add(customer Customer) {
    c.customers = append(c.customers, customer) // 叠加
}

func (c *CustomerCol) Accept(visitor Visitor) { // 每个服务者都接手访问者
    for _, customer := range c.customers {
        customer.Accept(visitor)
    }
}

创建文件AnalysisVisitor.go

package visitor

import "fmt"

type AnalysisVisitor struct {
}

func (*AnalysisVisitor) Visit(customer Customer) {
    switch c := customer.(type) {
    case *EnterpriseCustomer:
        fmt.Println("analysis enterprise customer", c.name)
    }
}

创建文件ServiceRequestVisitor.go

package visitor

import "fmt"

type ServiceRequestVisitor struct {
}

func (*ServiceRequestVisitor) Visit(customer Customer) {
    switch c := customer.(type) {
    case *EnterpriseCustomer:
        fmt.Println("serving enterprise customer", c.name)
    case *IndividualCustomer:
        fmt.Println("serving individual customer", c.name)
    }
}

main.go

package main

import "ssp_api_go/test/design/visitor"

func main() {
    c := visitor.CustomerCol{}
    c.Add(visitor.NewEnterpriseCustomer("Microsoft"))
    //c.Add(visitor.NewEnterpriseCustomer("Google"))
    c.Add(visitor.NewIndividualCustomer("Billgates"))
    c.Add(visitor.NewEnterpriseCustomer("Google"))
    //c.Accept(&visitor.ServiceRequestVisitor{})
    c.Accept(&visitor.AnalysisVisitor{})
}

 

发表评论

邮箱地址不会被公开。 必填项已用*标注

Go