-
Notifications
You must be signed in to change notification settings - Fork 0
/
observer.go
92 lines (76 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import "fmt"
/*
Observer--->subscribe--->Subject
Subject--->notify--->Observer
*/
// Subject ------------Subject-------------
type Subject interface {
register(observer Observer)
unregister(observer Observer)
notifyAll()
}
type item struct {
observerList []Observer
//self-attributes
name string
inStock bool
}
func newItem(name string) *item {
return &item{
name: name,
}
}
func (t *item) register(observer Observer) {
t.observerList = append(t.observerList, observer)
}
func (t *item) unregister(observer Observer) {
t.observerList = removeFromSlice(t.observerList, observer)
}
func (t *item) notifyAll() {
for _, observer := range t.observerList {
observer.update(t.name)
}
}
func (t *item) updateAvailability() {
fmt.Printf("Item %s is now in stock\n", t.name)
t.inStock = true
t.notifyAll()
}
func removeFromSlice(observerList []Observer, observer Observer) []Observer {
l := len(observerList)
for i, o := range observerList {
if o.getID() == observer.getID() {
observerList[l-1], observerList[i] = observerList[i], observerList[l-1]
return observerList[:l-1]
}
}
return observerList
}
// Observer ------------Observer-------------
type Observer interface {
update(subjectMessage string)
getID() string
}
type customer struct {
id string
}
func (c *customer) update(subjectMessage string) {
fmt.Printf("Sending email to customer %s for item %s\n", c.id, subjectMessage)
}
func (c *customer) getID() string {
return c.id
}
//RunObserverSubject gives simple example of how this works
func RunObserverSubject() {
shirtItem := newItem("regular-size shirt")
observerA := &customer{
id: "fake_email_A",
}
observerB := &customer{
id: "fake_email_B",
}
shirtItem.register(observerA)
shirtItem.register(observerB)
shirtItem.updateAvailability()
}