forked from senghoo/golang-design-pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |