在Java中,单例模式的实现主要依靠类中的静态字段。在Go语言中,没有静态类成员,所以我们使用的包访问机制和函数来提供类似的功能。来看下下面的例子:
package singleton import ( "fmt" ) type Singleton interface { SaySomething() } type singleton struct { text string } var oneSingleton Singleton func NewSingleton(text string) Singleton { if oneSingleton == nil { oneSingleton = &singleton{ text: text,} } return oneSingleton } func (this *singleton) SaySomething() { fmt.Println(this.text) }
来测试下:
package main import ( "Singleton/singleton" ) func main() { mSingleton,nSingleton := singleton.NewSingleton("hello"),singleton.NewSingleton("hi") mSingleton.SaySomething() nSingleton.SaySomething() } //----------------------- goroutine 测试 ------------------------ func main() { c := make(chan int) go newObject("hello",c) go newObject("hi",c) <-c <-c } func newObject(str string,c chan int) { nSingleton := singleton.NewSingleton(str) nSingleton.SaySomething() c <- 1 }
输出结果: