Golang singleton singleton pattern

In Java, to achieve Singleton pattern mainly depends on the class of static fields. In the Go language, no static class members, so the package access mechanism and function that we use to provide similar functionality. Look at the following example:

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) 
}


To test the next:

package main 
                        
import ( 
    "Hello/singleton"

                        
func main() { 
    mSingleton, nSingleton := singleton.NewSingleton("hello"), singleton.NewSingleton("hi") 
    mSingleton.SaySomething() 
    nSingleton.SaySomething() 
}

Output:

Golang singleton singleton pattern

Related Reading:

Golang by Thrift perfect framework for cross-language calling  http://www.linuxidc.com/Linux/2013-09/90748.htm

golang in how to convert a pointer to a struct Slice  http://www.linuxidc.com/Linux/2013-04/83106.htm

Ubuntu  install language packs Go  http://www.linuxidc.com/Linux/2013-05/85171.htm

"Go programming language" HD full version e-book  http://www.linuxidc.com/Linux/2013-05/84709.htm

Go parallel the beauty of language - beyond "the Hello World"  http://www.linuxidc.com/Linux/2013-05/83697.htm

Why I like the Go language  http://www.linuxidc.com/Linux/2013-05/84060.htm

 

Guess you like

Origin www.cnblogs.com/ExMan/p/11454011.html