-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathass2.go
83 lines (71 loc) · 1.57 KB
/
ass2.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
package main
import (
"fmt"
)
type observer interface {
handleEvent(vacancies []string)
}
type observable interface {
subscribe(o observer)
unsubscribe(o observer)
sendAll()
}
type Person struct {
name string
}
func (p *Person) handleEvent(vacancies []string) {
fmt.Println("Hello " + p.name)
fmt.Println("Vacancies updated: ")
for _, vacancy := range vacancies {
fmt.Println(vacancy)
}
}
type JobWebsite struct {
name string
vacancies []string
subscribers []observer
}
func (w *JobWebsite) addVacancy(vacancy string) {
w.vacancies = append(w.vacancies, vacancy)
w.sendAll()
}
func (w *JobWebsite) removeVacancy(vacancy string) {
index := 0
for sindex, wvacancy := range w.vacancies {
if wvacancy == vacancy {
index = sindex
}
}
w.vacancies = append(w.vacancies[:index], w.vacancies[index+1:]...)
w.sendAll()
}
func (w *JobWebsite) subscribe(o observer) {
w.subscribers = append(w.subscribers, o)
}
func (w *JobWebsite) unsubscribe(o observer) {
index := 0
for sindex, subscribe := range w.subscribers {
if subscribe == o {
index = sindex
}
}
w.subscribers = append(w.subscribers[:index], w.subscribers[index+1:]...)
}
func (w *JobWebsite) sendAll() {
for _, subscriber := range w.subscribers {
subscriber.handleEvent(w.vacancies)
}
}
func main() {
bob := Person{name: "Bob"}
hhKZ := JobWebsite{name: "hhkz"}
hhKZ.subscribe(&bob)
hhKZ.addVacancy("1")
hhKZ.addVacancy("2")
pop := Person{name: "Pip"}
hhKZ.subscribe(&pop)
hhKZ.addVacancy("3")
fmt.Println("--------------------")
hhKZ.unsubscribe(&pop)
hhKZ.removeVacancy("1")
}