Go 语言实现 23 种设计模式(修饰器)
生活随笔
收集整理的這篇文章主要介紹了
Go 语言实现 23 种设计模式(修饰器)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
修飾器
修飾器模式就是在不改變對(duì)象內(nèi)部結(jié)構(gòu)的情況下,動(dòng)態(tài)擴(kuò)展它的功能。
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 TshirtExample_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總結(jié)
以上是生活随笔為你收集整理的Go 语言实现 23 种设计模式(修饰器)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 80魔神力量1800独立1750攻击64
- 下一篇: Go 语言实现 23 种设计模式 单例模