golang實現單例模式

思維的深度發表於2018-05-10
package main

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]


相關文章