forked from go/golangs_learn
VIVIMAN
3 years ago
4 changed files with 101 additions and 6 deletions
@ -1 +1,60 @@ |
|||
package observer |
|||
|
|||
import ( |
|||
"sync" |
|||
"time" |
|||
|
|||
"github.com/pingcap/log" |
|||
) |
|||
|
|||
type Event struct { |
|||
Data int |
|||
} |
|||
|
|||
type Observer interface { |
|||
NotifyCallback(event Event) |
|||
} |
|||
|
|||
type Subject interface { |
|||
AddListener(observer Observer) |
|||
RemoveListener(observer Observer) |
|||
Notity(event Event) |
|||
} |
|||
|
|||
type eventObserver struct { |
|||
ID int |
|||
Time time.Time |
|||
} |
|||
|
|||
type eventSubject struct { |
|||
Observer sync.Map |
|||
} |
|||
|
|||
func (e *eventObserver) NotityCallback(event Event) { |
|||
log.Info("输出:%s, 之后输出:%s。", event.Data, time.Since(e.Time)) |
|||
} |
|||
|
|||
func (e *eventSubject) AddListener(observer Observer) { |
|||
e.Observer.Store(observer, struct{}{}) |
|||
} |
|||
|
|||
func (e *eventSubject) Notity(event Event) { |
|||
e.Observer.Range(func(key, value interface{}) bool { |
|||
if key == nil { |
|||
return false |
|||
} |
|||
key.(Observer).NotifyCallback(event) |
|||
return true |
|||
}) |
|||
} |
|||
|
|||
func Fib(n int) chan int { |
|||
c := make(chan int) |
|||
go func() { |
|||
defer close(c) |
|||
for i, j := 0, 1; i < n; i, j = i+j, i { |
|||
c <- i |
|||
} |
|||
}() |
|||
return c |
|||
} |
|||
|
@ -0,0 +1,32 @@ |
|||
package observer |
|||
|
|||
import ( |
|||
"reflect" |
|||
"testing" |
|||
) |
|||
|
|||
func TestFib(t *testing.T) { |
|||
type args struct { |
|||
n int |
|||
} |
|||
tests := []struct { |
|||
name string |
|||
args args |
|||
want chan int |
|||
}{ |
|||
{ |
|||
name: "测试管道函数-斐波那契数列", |
|||
args: args{ |
|||
n: 50, |
|||
}, |
|||
want: make(chan int), |
|||
}, |
|||
} |
|||
for _, tt := range tests { |
|||
t.Run(tt.name, func(t *testing.T) { |
|||
if got := Fib(tt.args.n); !reflect.DeepEqual(got, tt.want) { |
|||
t.Errorf("Fib() = %v, want %v", got, tt.want) |
|||
} |
|||
}) |
|||
} |
|||
} |
@ -0,0 +1,7 @@ |
|||
|
|||
```go |
|||
|
|||
``` |
|||
* 观察者模式 |
|||
|
|||
* |
Loading…
Reference in new issue