-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mediator.go
82 lines (70 loc) · 1.56 KB
/
Mediator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"fmt"
)
type IMediator interface {
Communicate(string, ICountry)
}
type Mediator struct {
cn ChinaCountry
us AmericaCountry
}
func (m *Mediator) Communicate(msg string, country ICountry) {
// 中国发msg米国收,否则相反
if country.GetName() == "China" {
m.us.ReceiveMessage(msg)
} else {
m.cn.ReceiveMessage(msg)
}
}
type ICountry interface {
Country(string, IMediator)
GetName() string
SendMessage(string)
ReceiveMessage(string)
}
type ChinaCountry struct {
ICountry
CountryName string
mediator IMediator
}
func (i *ChinaCountry) Country(name string, mediator IMediator) {
i.mediator = mediator
i.CountryName = name
}
func (i *ChinaCountry) GetName() string {
return i.CountryName
}
func (i *ChinaCountry) SendMessage(msg string) {
i.mediator.Communicate(msg, i)
}
func (i *ChinaCountry) ReceiveMessage(msg string) {
fmt.Println("cn received.")
}
type AmericaCountry struct {
ICountry
CountryName string
mediator IMediator
}
func (i *AmericaCountry) Country(name string, mediator IMediator) {
i.mediator = mediator
i.CountryName = name
}
func (i *AmericaCountry) GetName() string {
return i.CountryName
}
func (i *AmericaCountry) SendMessage(msg string) {
i.mediator.Communicate(msg, i)
}
func (i *AmericaCountry) ReceiveMessage(msg string) {
fmt.Println("cn received.")
}
func main() {
//定义的时候,接口实现的是指针接收,所以用指针初始化
m := new(Mediator)
cn := new(ChinaCountry)
us := new(AmericaCountry)
cn.Country("China", m)
us.Country("America", m)
cn.SendMessage("Hello")
}