go语言设计模式之observer
Posted aguncn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go语言设计模式之observer相关的知识,希望对你有一定的参考价值。
observer.go
package observer import ( "fmt" ) type Observer interface { Notify(string) } type Publisher struct { ObserversList []Observer } func (s *Publisher) AddObserver(o Observer) { s.ObserversList = append(s.ObserversList, o) } func (s *Publisher) RemoveObserver(o Observer) { var indexToRemove int for i, observer := range s.ObserversList { if observer == o { indexToRemove = i break } } s.ObserversList = append(s.ObserversList[:indexToRemove], s.ObserversList[indexToRemove+1:]...) } func (s *Publisher) NotifyObservers(m string) { fmt.Printf("Publisher received message ‘%s‘ to notify observers ", m) for _, observer := range s.ObserversList { observer.Notify(m) } }
observer_test.go
package observer import ( "fmt" "testing" ) type TestObserver struct { ID int Message string } func (p *TestObserver) Notify(m string) { fmt.Printf("Observer %d: message ‘%s‘ received ", p.ID, m) p.Message = m } func TestSubject(t *testing.T) { testObserver1 := &TestObserver{1, ""} testObserver2 := &TestObserver{2, ""} testObserver3 := &TestObserver{3, ""} publisher := Publisher{} t.Run("AddObserver", func(t *testing.T) { publisher.AddObserver(testObserver1) publisher.AddObserver(testObserver2) publisher.AddObserver(testObserver3) if len(publisher.ObserversList) != 3 { t.Fail() } }) t.Run("RemoveObserver", func(t *testing.T) { publisher.RemoveObserver(testObserver2) fmt.Println(publisher.ObserversList) if len(publisher.ObserversList) != 2 { t.Error("The size of the observer list is not 2.") } for _, observer := range publisher.ObserversList { testObserver, ok := observer.(*TestObserver) if !ok { t.Fail() } if testObserver.ID == 2 { t.Fail() } } }) t.Run("Notify", func(t *testing.T) { for _, observer := range publisher.ObserversList { printObserver, ok := observer.(*TestObserver) if !ok { t.Fail() break } if printObserver.Message != "" { t.Error("The observer‘s Message field weren‘t empty.") } } message := "Hello World" publisher.NotifyObservers(message) for _, observer := range publisher.ObserversList { printObserver, ok := observer.(*TestObserver) if !ok { t.Fail() break } if printObserver.Message != message { t.Errorf("Expected message on observer %d was "+ "not expected: ‘%s‘ != ‘%s‘ ", printObserver.ID, printObserver.Message, message) } } }) }
以上是关于go语言设计模式之observer的主要内容,如果未能解决你的问题,请参考以下文章
JAVA SCRIPT设计模式--行为型--设计模式之Observer观察者模式(19)