golang 设计模式之单例模式

65 阅读1分钟

第一种:lock模式

package main

import (
 "fmt"
 "sync"
 "time"
)

type singleton struct{

 date time.Time
}
var (
 instance *singleton
 lock     sync.Mutex
)

func GetInstance()*singleton{
 lock.Lock()
 defer lock.Unlock()
 if instance==nil{
    instance = &singleton{
    date :time.Now(),
    }
 }
 return instance
}
func main(){
 s:=GetInstance()
 fmt.Println(s.date)
 time.Sleep(time.Second*2)

 s1:=GetInstance()
 fmt.Println(s1.date)
}
  1. sync.Once 模式
package main

import (
 "fmt"
 "sync"
 "time"
)

type Singleton struct{

 date time.Time
}
func (s *Singleton)doSomeThing(){
 s.date = time.Now()
}

var (
 once sync.Once
 sing *Singleton
)
func GetInstance()*Singleton{

 once.Do(func(){
    sing= &Singleton{}
    sing.doSomeThing()
 })
 return sing
}

func main(){
 s:=GetInstance()
 fmt.Println(s.date)

 time.Sleep(time.Second*2)
 s1:=GetInstance()
 fmt.Println(s1.date)
}