Skip to content

Commit

Permalink
add observer mode
Browse files Browse the repository at this point in the history
  • Loading branch information
senghoo committed Mar 26, 2016
1 parent 2e5f90b commit e1a9fd0
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
47 changes: 47 additions & 0 deletions 10_observer/oberser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
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)
}
17 changes: 17 additions & 0 deletions 10_observer/oberser_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package observer

func ExampleObserver() {
subject := NewSubject()
reader1 := NewReader("reader1")
reader2 := NewReader("reader2")
reader3 := NewReader("reader3")
subject.Attach(reader1)
subject.Attach(reader2)
subject.Attach(reader3)

subject.UpdateContext("observer mode")
// Output:
// reader1 receive observer mode
// reader2 receive observer mode
// reader3 receive observer mode
}

0 comments on commit e1a9fd0

Please sign in to comment.