单例模式(每次严格返回一个实例):模拟打印机的使用场景
import (
"sync"
"fmt"
"time"
)
type Printer struct {}
var (
Single *Printer //打印机实例
once sync.Once //保证只执行一次方法
mutex sync.Mutex //锁对象
)
func New() *Printer{
once.Do(func() {
Single = &Printer{}
})
return Single
}
func (this *Printer) Print(content string) {
//加锁
mutex.Lock()
fmt.Println("content is:", content)
fmt.Print("print time is:", time.Now().Format(time.RFC3339))
//模拟等待打印时间
time.Sleep(time.Second * 1)
//解锁
mutex.Unlock()
}
package main
import (
single "learn/design-pattern/my"
"time"
)
func main() {
go single.New().Print("Hello World 1")
go single.New().Print("Hello World 2")
go single.New().Print("Hello World 3")
time.Sleep(time.Second * 5)
}
可以从结果中看到,三个线程同时去打印并没有产生争夺资源的情况。