Skip to content

Instantly share code, notes, and snippets.

@tawateer
Created November 5, 2015 04:00
Show Gist options
  • Save tawateer/cef2cfa2013d9e53e76b to your computer and use it in GitHub Desktop.
Save tawateer/cef2cfa2013d9e53e76b to your computer and use it in GitHub Desktop.
go 的单例
import (
"singleton"
)
func main() {
mSingleton, nSingleton := singleton.NewSingleton("hello"), singleton.NewSingleton("hi")
mSingleton.SaySomething()
nSingleton.SaySomething()
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
}
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment