-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathobserver.go
54 lines (45 loc) · 1.11 KB
/
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
// Package observer is an example of the Observer Pattern.
// Push model.
package observer
// Publisher interface.
type Publisher interface {
Attach(observer Observer)
SetState(state string)
Notify()
}
// Observer provides a subscriber interface.
type Observer interface {
Update(state string)
}
// ConcretePublisher implements the Publisher interface.
type ConcretePublisher struct {
observers []Observer
state string
}
// NewPublisher is the Publisher constructor.
func NewPublisher() Publisher {
return &ConcretePublisher{}
}
// Attach a Observer
func (s *ConcretePublisher) Attach(observer Observer) {
s.observers = append(s.observers, observer)
}
// SetState sets new state
func (s *ConcretePublisher) SetState(state string) {
s.state = state
}
// Notify sends notifications to subscribers.
// Push model.
func (s *ConcretePublisher) Notify() {
for _, observer := range s.observers {
observer.Update(s.state)
}
}
// ConcreteObserver implements the Observer interface.
type ConcreteObserver struct {
state string
}
// Update set new state
func (s *ConcreteObserver) Update(state string) {
s.state = state
}