? ? ? ? Go語言中,實現單例模式的方式有很多種。單例模式確保一個類只有一個實例,并提供一個全局訪問點。Go語言沒有類的概念,但是可以通過結構體、函數和包級變量來實現類似的功能。
懶漢實現
type Product interface {DoSomething()
}type singletonProduct struct{}func (p *singletonProduct) DoSomething() {}var instanceOnce struct {instance Productonce sync.Once
}func GetInstance() Product {instanceOnce.once.Do(func() {instanceOnce.instance = &singletonProduct{}})return instanceOnce.instance
}
- singletonProduct使用小寫開頭,防止使用者自己創建實例,提供GetInstance方法作為獲取實例的唯一入口。
- 使用sync.Once處理單次創建問題。
餓漢實現
package singletontype Product interface {DoSomething()
}type singletonProduct struct{}func (p *singletonProduct) DoSomething() {}var instance = &singletonProduct{}func GetInstance() Product {return instance
}
- 利用Go的包初始化機制,在程序啟動時就創建實例。