forked from bvwells/go-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
observer.go
73 lines (60 loc) · 1.78 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package behavioral
import (
"fmt"
"io"
"os"
)
var outputWriter io.Writer = os.Stdout // modified during testing
// Event describes an event to observe and notify on.
type Event struct {
id string
}
// EventObserver describes an interface for observing events.
type EventObserver interface {
OnNotify(event Event)
}
// observer is an implementation of the EventObserver interface.
type observer struct {
name string
}
// NewEventObserver returns a new instance of an EventObserver.
func NewEventObserver(name string) EventObserver {
return &observer{name}
}
// OnNotify logs the event being notified on.
func (o *observer) OnNotify(event Event) {
fmt.Fprintf(outputWriter, "observer '%s' received event '%s'\n", o.name, event.id)
}
// EventNotifier describes an interface for registering and de-registering observers to
// be notified when an event occurs.
type EventNotifier interface {
Register(obs EventObserver)
Deregister(obs EventObserver)
Notify(event Event)
}
// eventNotifer is an implementation of the EventNotifier interface.
type eventNotifer struct {
observers []EventObserver
}
// NewEventNotifier returns a new instance of an EventNotifier.
func NewEventNotifier() EventNotifier {
return &eventNotifer{}
}
// Register registers a new observer for notifying on.
func (e *eventNotifer) Register(obs EventObserver) {
e.observers = append(e.observers, obs)
}
// Deregister de-registers an observer for notifying on.
func (e *eventNotifer) Deregister(obs EventObserver) {
for i := 0; i < len(e.observers); i++ {
if obs == e.observers[i] {
e.observers = append(e.observers[:i], e.observers[i+1:]...)
}
}
}
// Notify notifies all observers on an event.
func (e *eventNotifer) Notify(event Event) {
for i := 0; i < len(e.observers); i++ {
e.observers[i].OnNotify(event)
}
}