学习Go语言之观察者模式

首先了解一下观察者模式

1.目标和观察者抽象对象需要首先建立

 1 //抽象主题
 2 type Subject interface {
 3     Add(o Observer)
 4     Send(str string)
 5 }
 6 
 7 //抽象观察者
 8 type Observer interface {
 9     Receive(str string)
10 }

2.主题的具体实现

 1 //-------------天气主题------------------
 2 type NewsSubject struct {
 3     title string
 4     l     *list.List
 5 }
 6 
 7 //天气主题非侵入式实现抽象主题
 8 func (sub *NewsSubject) Add(o Observer) {
 9     sub.l.PushBack(o)
10 }
11 
12 //天气主题非侵入式实现抽象主题
13 func (sub *NewsSubject) Send(str string) {
14     for i := sub.l.Front(); i != nil; i = i.Next() {
15         (i.Value).(Observer).Receive(sub.title + "发送的:" + str)
16     }
17 }
18 
19 //-------------热点主题------------------
20 type HotSubject struct {
21     title string
22     l     *list.List
23 }
24 
25 //热点主题非侵入式实现抽象主题
26 func (sub *HotSubject) Add(o Observer) {
27     sub.l.PushBack(o)
28 }
29 
30 //热点主题非侵入式实现抽象主题
31 func (sub *HotSubject) Send(str string) {
32     for i := sub.l.Front(); i != nil; i = i.Next() {
33         (i.Value).(Observer).Receive(sub.title + "发送的:" + str)
34     }
35 }

3.观察者具体实现

 1 //-------------a观察者------------------
 2 type aObserver struct {
 3     name string
 4 }
 5 
 6 //a观察者非侵入式实现抽象观察者
 7 func (o *aObserver) Receive(str string) {
 8     fmt.Println("A类观察者【" + o.name + "】接收" + str)
 9 }
10 
11 //-------------b观察者------------------
12 type bObserver struct {
13     name string
14 }
15 
16 //b观察者非侵入式实现抽象观察者
17 func (o *bObserver) Receive(str string) {
18     fmt.Println("B类观察者【" + o.name + "】接收" + str)
19 }

4.实际调用

 1 func main() {
 2     a := &aObserver{
 3         name: "张三",
 4     }
 5 
 6     b := &bObserver{
 7         name: "李四",
 8     }
 9 
10     //新闻允许a和b类型观察者订阅
11     news := NewsSubject{
12         l:     list.New(),
13         title: "武汉新闻",
14     }
15     news.Add(a)
16     news.Add(b)
17 
18     //热点只允许b类型观察者订阅
19     hot := HotSubject{
20         l:     list.New(),
21         title: "孝感热点",
22     }
23     hot.Add(b)
24 
25     news.Send("全省暴雨红色警报")
26     hot.Send("全市停工停课")
27 }

5.运行结果

猜你喜欢

转载自www.cnblogs.com/shi2310/p/10941626.html