go 示例
最后更新于:2022-04-02 04:19:28
[TOC]
## 示例
### 概念示例
输出 ``` Creating single instance now. Single instance already created1. Single instance already created2. Single instance already created1. Single instance already created1. ``` ### 使用 init 函数 我们可以在`init`函数中创建单例实例。这仅适用于实例的早期初始化工作已经确定时。`init`函数仅会在包中的每个文件里调用一次,所以我们可以确定其只会创建一个实例。 ### sync.Once [推荐] sync.Once仅会执行一次操作
输出 ``` Creating single instance now. Single instance already created. Single instance already created. Single instance already created. ```
';
main.go
``` package main import ( "fmt" "sync" ) var lock = sync.Mutex{} type single struct { } var singleInstance *single func getInstance() *single { if singleInstance == nil { lock.Lock() defer lock.Unlock() if singleInstance == nil { fmt.Println("Creating single instance now.") singleInstance = &single{} } else { fmt.Println("Single instance already created1.") } } else { fmt.Println("Single instance already created2.") } return singleInstance } func main() { for i := 0; i < 5; i++ { go getInstance() } fmt.Scanln() } ```输出 ``` Creating single instance now. Single instance already created1. Single instance already created2. Single instance already created1. Single instance already created1. ``` ### 使用 init 函数 我们可以在`init`函数中创建单例实例。这仅适用于实例的早期初始化工作已经确定时。`init`函数仅会在包中的每个文件里调用一次,所以我们可以确定其只会创建一个实例。 ### sync.Once [推荐] sync.Once仅会执行一次操作
main.go
``` package main import ( "fmt" "sync" ) var once sync.Once type single struct { } var singleInstance *single func getInstance() *single { if singleInstance == nil { once.Do( func() { fmt.Println("Creating single instance now.") singleInstance = &single{} }) } else { fmt.Println("Single instance already created.") } return singleInstance } func main() { for i := 0; i < 5; i++ { go getInstance() } fmt.Scanln() } ```输出 ``` Creating single instance now. Single instance already created. Single instance already created. Single instance already created. ```