-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver_pattern.go
More file actions
84 lines (66 loc) · 1.51 KB
/
observer_pattern.go
File metadata and controls
84 lines (66 loc) · 1.51 KB
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
package main
import (
"fmt"
"sync"
)
// All observers must implement this interface
type Observer interface {
Update(stock string, price float64)
}
// Subject being observed
type Stock struct {
name string
price float64
observers map[Observer]struct{}
mu sync.Mutex // Ensures thread safety
}
// Constructor
func NewStock(name string, price float64) *Stock {
return &Stock{
name: name,
price: price,
observers: make(map[Observer]struct{}),
}
}
func (s *Stock) AddObserver(ob Observer) {
s.mu.Lock()
defer s.mu.Unlock()
s.observers[ob] = struct{}{}
}
func (s *Stock) RemoveObserver(ob Observer) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.observers, ob)
}
func (s *Stock) NotifyObservers() {
s.mu.Lock()
defer s.mu.Unlock()
for ob := range s.observers {
ob.Update(s.name, s.price)
}
}
func (s *Stock) SetPrice(price float64) {
fmt.Printf("\n[Market Update] %s price updated to $%.2f\n", s.name, price)
s.price = price
s.NotifyObservers()
}
// Investor Observer
type Investor struct {
name string
}
func (i *Investor) Update(stock string, price float64) {
fmt.Printf("[Investor %s] Alert! %s is now $%.2f\n", i.name, stock, price)
}
func main() {
tesla := NewStock("Tesla", 100.00)
alice := &Investor{name: "alice"}
bob := &Investor{name: "bob"}
tesla.AddObserver(alice)
tesla.AddObserver(bob)
// bob and alice recieves the updates
tesla.SetPrice(920.50)
tesla.SetPrice(550.60)
tesla.RemoveObserver(alice)
// bob only recieves updates
tesla.SetPrice(1120.00)
}