diff --git a/golang_learn/data_prattern/abstract_factory/main_test.go b/golang_learn/data_prattern/abstract_factory/main_test.go index 655a188..eb39de5 100644 --- a/golang_learn/data_prattern/abstract_factory/main_test.go +++ b/golang_learn/data_prattern/abstract_factory/main_test.go @@ -1,13 +1,10 @@ package abstract_factory import ( - "reflect" "testing" ) - func TestNewSimpleLunchFactory(t *testing.T) { - NewSimpleLunchFactory().CreateFood().Cook() NewSimpleLunchFactory().CreateVegetable().Cook() } @@ -18,9 +15,9 @@ func TestTomato_Cook(t *testing.T) { tr *Tomato }{ { - name: "测试123", - tr: &Tomato{}, - } + name: "测试123", + tr: &Tomato{}, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/golang_learn/data_prattern/observer/main.go b/golang_learn/data_prattern/observer/main.go index 0483094..225846f 100644 --- a/golang_learn/data_prattern/observer/main.go +++ b/golang_learn/data_prattern/observer/main.go @@ -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 +} diff --git a/golang_learn/data_prattern/observer/main_test.go b/golang_learn/data_prattern/observer/main_test.go new file mode 100644 index 0000000..74e0d85 --- /dev/null +++ b/golang_learn/data_prattern/observer/main_test.go @@ -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) + } + }) + } +} diff --git a/golang_learn/data_prattern/observer/说明.md b/golang_learn/data_prattern/observer/说明.md new file mode 100644 index 0000000..4c0dcd0 --- /dev/null +++ b/golang_learn/data_prattern/observer/说明.md @@ -0,0 +1,7 @@ + +```go + +``` +* 观察者模式 + +* \ No newline at end of file