1.能夠複用一些寫法。常常在單元測試過程當中須要new一些對象能夠new的操做抽離出來
package main
import "fmt"
type S struct {
}
func (s *S) Service1(name string) {
fmt.Println("Service 1", name)
}
func (s *S) Service2(name string) {
fmt.Println("Service 2", name)
}
func (s *S) Service3(name string) {
fmt.Println("Service 3", name)
}
func newService() *S {
return &S{}
}
func withService(fn func(s *S)) func() {
return func() {
fn(newService())
}
}
func main() {
withService(func(s *S) {
s.Service1("first")
})()
withService(func(s *S) {
s.Service2("second")
})()
withService(func(s *S) {
s.Service3("third")
})()
}
2.中間件
package main
import (
"fmt"
"time"
)
func work(name string) {
fmt.Println("hello ", name)
time.Sleep(time.Second)
}
func calTime(f func(name string)) func(string) {
t := time.Now()
return func(n string) {
defer func() {
fmt.Println("time spend is ", time.Since(t))
}()
f(n)
}
}
func main() {
s := calTime(work)
s("world")
}