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的冪等。

更多內容請關注每日編程,每天進步一點。


分享到:


相關文章: