单例模式:限制类的实例,保证一个类只有一个实例。
Singleton creational design pattern restricts the instantiation of a type to a single object.
Implementation1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17package singleton
type singleton map[string]string
var (
once sync.Once
instance singleton
)
func New() singleton {
once.Do(func() {
instance = make(singleton)
})
return instance
}
Usage1
2
3
4
5
6
7
8s := singleton.New()
s["this"] = "that"
s2 := singleton.New()
fmt.Println("This is ", s2["this"])
// This is that
Rules of Thumb
Singleton pattern represents a global state and most of the time reduces testability.
单例模式表示全局状态,大多数时间减少了可测试性。