From 310206ad6828d8a41392239dbf9b0b1b91411f89 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Sat, 16 Nov 2024 14:10:32 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=89=87=E5=87=BA=E8=A7=82?= =?UTF-8?q?=E5=AF=9F=E8=80=85=E7=A4=BA=E4=BE=8B=E7=9A=84=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- observer/observer.go | 23 +++++++++++------------ observer/observer_test.go | 1 + 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/observer/observer.go b/observer/observer.go index 2c6f6c6..de5c125 100644 --- a/observer/observer.go +++ b/observer/observer.go @@ -17,16 +17,16 @@ func NewSubject() Subject { } // Attach 观察者绑定 -func (s *Subject) Attach(observer ...Observer) { - s.observers = append(s.observers, observer...) +func (s *Subject) Attach(obs ...Observer) { + s.observers = append(s.observers, obs...) } // Detach 观察者解绑 -func (s *Subject) Detach(observer Observer) { - for i, obs := range s.observers { - if obs == observer { +func (s *Subject) Detach(obs Observer) { + for i, o := range s.observers { + if o == obs { s.observers = append(s.observers[:i], s.observers[i+1:]...) - close(observer) + close(obs) break } } @@ -34,18 +34,17 @@ func (s *Subject) Detach(observer Observer) { // Notify 通知观察者 func (s *Subject) Notify(data any) { + // 这里可考虑不需要使用协程运行 go s.fanOut(s.in, s.observers) s.in <- data } // fanOut 扇出模式实现 func (s *Subject) fanOut(ch <-chan interface{}, out []Observer) { - var cases []reflect.SelectCase - // 添加输入 chan 的 reflect.SelectCase - cases = append(cases, reflect.SelectCase{ - Dir: reflect.SelectRecv, - Chan: reflect.ValueOf(ch), - }) + // 绑定输入 chan 的 reflect.SelectCase + cases := []reflect.SelectCase{ + {Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch)}, + } go func() { defer func() { diff --git a/observer/observer_test.go b/observer/observer_test.go index b2ac1c6..0754cdf 100644 --- a/observer/observer_test.go +++ b/observer/observer_test.go @@ -29,5 +29,6 @@ func TestObserver(t *testing.T) { newUser2 := "gan" userRegister.Notify(newUser1) userRegister.Notify(newUser2) + // 休眠防止主协程退出 time.Sleep(1 * time.Second) }