Skip to content

Commit 23a69b2

Browse files
committed
visitor demo
1 parent 256e4c3 commit 23a69b2

File tree

2 files changed

+118
-0
lines changed

2 files changed

+118
-0
lines changed

Visitor/demo.go

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package visitor
2+
3+
import "fmt"
4+
5+
type Action interface {
6+
GetManConclusion(Man)
7+
GetWomanConclusion(Woman)
8+
}
9+
10+
type Success struct {
11+
Name string
12+
}
13+
14+
func (s *Success) GetManConclusion(m Man) {
15+
if s == nil {
16+
return
17+
}
18+
fmt.Printf("%s %s 時, 背後多半有一個偉大的女人 \n", m.Name, s.Name)
19+
}
20+
21+
func (s *Success) GetWomanConclusion(w Woman) {
22+
if s == nil {
23+
return
24+
}
25+
fmt.Printf("%s %s 時, 背後多半有一個不成功的男人 \n", w.Name, s.Name)
26+
}
27+
28+
type Failing struct {
29+
Name string
30+
}
31+
32+
func (s *Failing) GetManConclusion(m Man) {
33+
if s == nil {
34+
return
35+
}
36+
fmt.Printf("%s %s 時, 悶頭喝酒, 誰也不用勸 \n", m.Name, s.Name)
37+
}
38+
39+
func (s *Failing) GetWomanConclusion(w Woman) {
40+
if s == nil {
41+
return
42+
}
43+
fmt.Printf("%s %s 時, 眼淚汪汪, 誰也勸不了 \n", w.Name, s.Name)
44+
}
45+
46+
type Person interface {
47+
Accept(Action)
48+
}
49+
50+
type Man struct {
51+
Name string
52+
}
53+
54+
func (m *Man) Accept(visitor Action) {
55+
if m == nil {
56+
return
57+
}
58+
visitor.GetManConclusion(*m)
59+
}
60+
61+
type Woman struct {
62+
Name string
63+
}
64+
65+
func (w *Woman) Accept(visitor Action) {
66+
if w == nil {
67+
return
68+
}
69+
visitor.GetWomanConclusion(*w)
70+
}
71+
72+
type ObjectStructurePerson struct {
73+
elemetes []Person
74+
}
75+
76+
func (o *ObjectStructurePerson) Attach(ele Person) {
77+
if o == nil || ele == nil {
78+
return
79+
}
80+
o.elemetes = append(o.elemetes, ele)
81+
}
82+
83+
func (o *ObjectStructurePerson) Detach(ele Person) {
84+
if o == nil || ele == nil {
85+
return
86+
}
87+
for i, val := range o.elemetes {
88+
if val == ele {
89+
o.elemetes = append(o.elemetes[:i], o.elemetes[i+1:]...)
90+
break
91+
}
92+
}
93+
}
94+
95+
func (o *ObjectStructurePerson) Accept(v Action) {
96+
if o == nil {
97+
return
98+
}
99+
for _, val := range o.elemetes {
100+
val.Accept(v)
101+
}
102+
}

Visitor/dmeo_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package visitor
2+
3+
import "testing"
4+
5+
func TestDemo(t *testing.T) {
6+
o := new(ObjectStructurePerson)
7+
o.Attach(&Man{"男人"})
8+
o.Attach(&Woman{"女人"})
9+
10+
// 成功
11+
conreteVA := &Success{"成功"}
12+
// 失敗
13+
conreteVB := &Failing{"失敗"}
14+
o.Accept(conreteVA)
15+
o.Accept(conreteVB)
16+
}

0 commit comments

Comments
 (0)