修饰器
修饰器模式就是在不改变对象内部结构的情况下,动态扩展它的功能。
Example_one
type Object func(string) stringfunc Decorate(fn Object) Object {return func(base string) string {ret := fn(base)ret = ret + " and Tshirt"return ret}
}func Dressing(cloth string) string {return "dressing " + cloth
}func main() {f := Decorate(Dressing)fmt.Println(f("shoes"))
}
> dressing shoes and Tshirt
Example_two
type piFunc func(int) float64// logger(cache(Pi(n)))
func wraplogger(fun piFunc, logger *log.Logger) piFunc {return func(n int) float64 {fn := func(n int) (result float64) {defer func(t time.Time) {logger.Printf("took=%v, n=%v, result=%v", time.Since(t), n, result)}(time.Now())return fun(n)}return fn(n)}
}// cache(logger(Pi(n)))
func wrapcache(fun piFunc, cache *sync.Map) piFunc {return func(n int) float64 {fn := func(n int) float64 {key := fmt.Sprintf("n=%d", n)val, ok := cache.Load(key)if ok {return val.(float64)}result := fun(n)cache.Store(key, result)return result}return fn(n)}
}func Pi(n int) float64 {ch := make(chan float64)for k := 0; k <= n; k++ {go func(ch chan float64, k float64) {ch <- 4 * math.Pow(-1, k) / (2*k + 1)}(ch, float64(k))}result := 0.0for k := 0; k <= n; k++ {result += <-ch}return result
}func main() {fw_pi := wrapcache(Pi, &sync.Map{})f_pi := wraplogger(fw_pi, log.New(os.Stdout, "test", 1))f_pi(10000)f_pi(10000)
}> test2020/05/28 took=157.4587ms, n=10000, result=3.141692643590535
> test2020/05/28 took=0s, n=10000, result=3.141692643590535