Created
November 5, 2015 04:00
-
-
Save tawateer/cef2cfa2013d9e53e76b to your computer and use it in GitHub Desktop.
go 的单例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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