Golang 单例模式

单例模式示例:

Golang 单例模式

import (

"sync"

"fmt"

)

type singleton map[string]string

var (

once sync.Once

instance singleton

)

func New() singleton {

once.Do(func() {

instance = make(singleton)

})

return instance

}

func main() {

s := New()

s["test1"] ="aa"

fmt.Println(s)

s1 := New() //没有重新初始化

s1["test2"] = "bb"

fmt.Println(s1)

}

打印结果:

map[test1:aa]

map[test1:aa test2:bb]

小结:单例模式主要考察知识点是sync.once的幂等。

更多内容请关注每日编程,每天进步一点。


分享到:


相關文章: