mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-26 13:46:03 +03:00
48 lines
681 B
Go
48 lines
681 B
Go
|
package observer
|
||
|
|
||
|
import "fmt"
|
||
|
|
||
|
type Subject struct {
|
||
|
observers []Observer
|
||
|
context string
|
||
|
}
|
||
|
|
||
|
func NewSubject() *Subject {
|
||
|
return &Subject{
|
||
|
observers: make([]Observer, 0),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (s *Subject) Attach(o Observer) {
|
||
|
s.observers = append(s.observers, o)
|
||
|
}
|
||
|
|
||
|
func (s *Subject) notify() {
|
||
|
for _, o := range s.observers {
|
||
|
o.Update(s)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (s *Subject) UpdateContext(context string) {
|
||
|
s.context = context
|
||
|
s.notify()
|
||
|
}
|
||
|
|
||
|
type Observer interface {
|
||
|
Update(*Subject)
|
||
|
}
|
||
|
|
||
|
type Reader struct {
|
||
|
name string
|
||
|
}
|
||
|
|
||
|
func NewReader(name string) *Reader {
|
||
|
return &Reader{
|
||
|
name: name,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (r *Reader) Update(s *Subject) {
|
||
|
fmt.Printf("%s receive %s\n", r.name, s.context)
|
||
|
}
|