|
| 1 | +package visitor |
| 2 | + |
| 3 | +import "fmt" |
| 4 | + |
| 5 | +type Customer interface { |
| 6 | + Accept(Visitor) |
| 7 | +} |
| 8 | + |
| 9 | +type Visitor interface { |
| 10 | + Visit(Customer) |
| 11 | +} |
| 12 | + |
| 13 | +type EnterpriseCustomer struct { |
| 14 | + name string |
| 15 | +} |
| 16 | + |
| 17 | +type CustomerCol struct { |
| 18 | + customers []Customer |
| 19 | +} |
| 20 | + |
| 21 | +func (c *CustomerCol) Add(customer Customer) { |
| 22 | + c.customers = append(c.customers, customer) |
| 23 | +} |
| 24 | + |
| 25 | +func (c *CustomerCol) Accept(visitor Visitor) { |
| 26 | + for _, customer := range c.customers { |
| 27 | + customer.Accept(visitor) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +func NewEnterpriseCustomer(name string) *EnterpriseCustomer { |
| 32 | + return &EnterpriseCustomer{ |
| 33 | + name: name, |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +func (c *EnterpriseCustomer) Accept(visitor Visitor) { |
| 38 | + visitor.Visit(c) |
| 39 | +} |
| 40 | + |
| 41 | +type IndividualCustomer struct { |
| 42 | + name string |
| 43 | +} |
| 44 | + |
| 45 | +func NewIndividualCustomer(name string) *IndividualCustomer { |
| 46 | + return &IndividualCustomer{ |
| 47 | + name: name, |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +func (c *IndividualCustomer) Accept(visitor Visitor) { |
| 52 | + visitor.Visit(c) |
| 53 | +} |
| 54 | + |
| 55 | +type ServiceRequestVisitor struct{} |
| 56 | + |
| 57 | +func (*ServiceRequestVisitor) Visit(customer Customer) { |
| 58 | + switch c := customer.(type) { |
| 59 | + case *EnterpriseCustomer: |
| 60 | + fmt.Printf("serving enterprise customer %s\n", c.name) |
| 61 | + case *IndividualCustomer: |
| 62 | + fmt.Printf("serving individual customer %s\n", c.name) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// only for enterprise |
| 67 | +type AnalysisVisitor struct{} |
| 68 | + |
| 69 | +func (*AnalysisVisitor) Visit(customer Customer) { |
| 70 | + switch c := customer.(type) { |
| 71 | + case *EnterpriseCustomer: |
| 72 | + fmt.Printf("analysis enterprise customer %s\n", c.name) |
| 73 | + } |
| 74 | +} |
0 commit comments