From 8a7bd86ed0716cc0b06cd2fe28e4fa22a60404ff Mon Sep 17 00:00:00 2001 From: Jian Han Date: Tue, 21 Nov 2017 23:12:41 +1000 Subject: [PATCH] observer pattern --- behavioral/observerpattern/main.go | 70 ++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 behavioral/observerpattern/main.go diff --git a/behavioral/observerpattern/main.go b/behavioral/observerpattern/main.go new file mode 100644 index 0000000..c734c0d --- /dev/null +++ b/behavioral/observerpattern/main.go @@ -0,0 +1,70 @@ +package main + +import ( + "reflect" + + "github.com/davecgh/go-spew/spew" +) + +type AbstractObserver interface { + Update(abstractSubject AbstractSubject) error +} + +type AbstractSubject interface { + Attach(abstractObserver AbstractObserver) + Detach(abstractObserver AbstractObserver) + Notify() + GetFav() string +} + +type PatternObserver struct { +} + +func (p *PatternObserver) Update(s AbstractSubject) error { + spew.Dump(" new favorite patterns", s.GetFav()) + return nil +} + +type PatternSubject struct { + FavoritePatterns []string + Observers []AbstractObserver + Fav string +} + +func (p *PatternSubject) Attach(observer AbstractObserver) { + p.Observers = append(p.Observers, observer) +} + +func (p *PatternSubject) Detach(observer AbstractObserver) { + for k, v := range p.Observers { + if reflect.DeepEqual(observer, v) { + p.Observers = append(p.Observers[:k], p.Observers[k+1:]...) + break + } + } +} + +func (p *PatternSubject) Notify() { + for _, v := range p.Observers { + v.Update(p) + } +} + +func (p *PatternSubject) updateFav(fav string) { + p.Fav = fav + p.Notify() +} + +func (p *PatternSubject) GetFav() string { + return p.Fav +} + +func main() { + patternGossiper := &PatternSubject{} + patternGossipFan := &PatternObserver{} + patternGossiper.Attach(patternGossipFan) + patternGossiper.updateFav("abstract factory, decorator, visitor") + patternGossiper.updateFav("abstract factory, observer, decorator") + patternGossiper.Detach(patternGossipFan) + patternGossiper.updateFav("abstract factory, observer, paisley") +}