纯函数实现双重闭包连接池懒加载功能模型,提升性能的利器

2019-01-06  本文已影响24人  funcx
package main

import (
    "fmt"
    "log"
    "os"
)

var logger = log.New(os.Stdout, "", log.LstdFlags|log.Lshortfile)

type conn struct {
    id int
}

func main() {
    connFunc := connFuncFactory()
    getFunc := connFunc("get")
    putFunc := connFunc("put")
    fmt.Println(getFunc())
    fmt.Println(getFunc())
    putFunc()
    fmt.Println(getFunc())
}

func connFuncFactory() func(def string) func() *conn {
    var c *conn
    return func(def string) func() *conn {
        switch def {
        case "get":
            return func() *conn {
                if c == nil {
                    logger.Println("新建连接")
                    c = &conn{id: 1}
                }
                return c
            }
        case "put":
            return func() *conn {
                logger.Println("释放连接")
                c = nil
                return nil
            }
        }
        panic("panic in case")
    }
}
上一篇 下一篇

猜你喜欢

热点阅读