-
Notifications
You must be signed in to change notification settings - Fork 2
/
observer.go
59 lines (44 loc) · 899 Bytes
/
observer.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
package main
import (
"fmt"
)
/*
Like the View in MVC. Lets Objects subscribe to changes in a Subject.
*/
func main() {
var subject Subject
NewObserver(&subject)
subject.SetState("crushing")
}
type Observer interface {
Notify()
}
type Subject struct {
observers []Observer
state string // for simplicity
}
func (s *Subject) SetState(state string) {
s.state = state
for _, observer := range s.observers {
observer.Notify()
}
}
func (s *Subject) GetState() string {
return s.state
}
func (s *Subject) Subscribe(observer Observer) {
s.observers = append(s.observers, observer)
}
type SomeObserver struct {
subject *Subject
}
func NewObserver(subject *Subject) {
var result = SomeObserver{
subject: subject,
}
subject.Subscribe(result)
}
func (s SomeObserver) Notify() {
fmt.Println("Thanks! Let me get the state")
fmt.Println("State:", s.subject.GetState())
}