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框架完美实现跨语言调用 http://www.linuxidc.com/Linux/2013-09/90748.htm

golang里如何将一个struct指针转换成slice http://www.linuxidc.com/Linux/2013-04/83106.htm

Ubuntu 安装Go语言包 http://www.linuxidc.com/Linux/2013-05/85171.htm

《Go语言编程》高清完整版电子书 http://www.linuxidc.com/Linux/2013-05/84709.htm

Go语言并行之美 -- 超越 “Hello World” http://www.linuxidc.com/Linux/2013-05/83697.htm

我为什么喜欢Go语言 http://www.linuxidc.com/Linux/2013-05/84060.htm

猜你喜欢

转载自www.cnblogs.com/ExMan/p/11454011.html