Golang 单例模式 singleton pattern


在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 (
    "Hello/singleton"
)
                       
func main() {
    mSingleton, nSingleton := singleton.NewSingleton("hello"), singleton.NewSingleton("hi")
    mSingleton.SaySomething()
    nSingleton.SaySomething()
}

输出结果:

Golang 单例模式 singleton pattern

Golang通过Thrift框架完美实现跨语言调用

golang里如何将一个struct指针转换成slice

Ubuntu 安装Go语言包

《Go语言编程》高清完整版电子书

Go语言并行之美 -- 超越 “Hello World”

我为什么喜欢Go语言

相关内容