Created
December 15, 2023 11:16
-
-
Save Guaderxx/7e45a67a1cde382855ad721d0c1ea9fd to your computer and use it in GitHub Desktop.
singleton
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 main | |
import "fmt" | |
type SingletonCon struct { | |
url string | |
port string | |
} | |
var singletonConInstance *SingletonCon | |
func GetInstance() *SingletonCon { | |
if singletonConInstance == nil { | |
fmt.Println("Create singleton instance") | |
singletonConInstance = &SingletonCon{ | |
url: "url", | |
port: "port", | |
} | |
} else { | |
fmt.Println("Singleton instance already created.") | |
} | |
return singletonConInstance | |
} | |
func main() { | |
for i := 0; i < 10; i++ { | |
GetInstance() | |
// This will executed 10 times | |
// use sync.Once | sync.OnceFunc | sync.Value | |
// only execute one time | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment