package main
import (
"fmt"
"sync"
)
/*
Singleton: 单例对象的类必须保证只有一个实例存在, 全局有唯一接口访问
1.懒汉模式:指全局的单例实例在第一次被使用是构建
缺点:非线程安全
*/
type singleton struct{}
var ins *singleton
var once sync.Once
func GetIns() *singleton {
once.Do(func() {
ins = &singleton{}
})
return ins
}
/*
2.饿汉模式:指全局的单例实例在类装载时构建
缺点:如果实例化复杂时,将会增加耗时
*/
type singletonehan struct{}
var insehan *singletonehan = &singletonehan{}
func GetInsehan() *singletonehan {
return insehan
}
/*
日常用的最多的是懒汉加锁, 保证了线程安全同时减少实例耗时
once.Do方法, Go语言提供了一个Once类型来保证全局的唯一性操作
*/
//===============================================================================================
/*
Singleton creational design pattern restricts the instantiation of a type to a single object
*/
type singletonex map[string]string
var (
once_only sync.Once
instance singletonex
)
func New() singletonex{
once_only.Do(func() {
instance = make(singletonex)
})
return instance
}
func main(){
//创建一个实例
s:=New()
s["1"] = "first"
s2:=New()
fmt.Println(s2) //print: map[1:first]
}