Home > Article > Backend Development > What are the application scenarios of singleton pattern in Golang?
Golang is an open source statically typed programming language that is efficient, powerful and concise. In Golang, the singleton pattern is a commonly used design pattern to ensure that a class has only one instance and provides a global access point. The singleton pattern can play a role in many scenarios. The following will introduce some scenarios suitable for applying the singleton pattern in Golang, and attach specific code examples.
package database import ( "database/sql" "sync" _ "github.com/go-sql-driver/mysql" ) var db *sql.DB var once sync.Once func GetDB() *sql.DB { once.Do(func() { var err error db, err = sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/dbname") if err != nil { panic(err) } }) return db }
package config import ( "github.com/spf13/viper" "sync" ) type Config struct { DatabaseUsername string DatabasePassword string } var instance *Config var once sync.Once func GetConfig() *Config { once.Do(func() { viper.SetConfigFile("config.yaml") viper.ReadInConfig() instance = &Config{ DatabaseUsername: viper.GetString("database.username"), DatabasePassword: viper.GetString("database.password"), } }) return instance }
package logger import ( "log" "sync" ) type Logger struct { } var instance *Logger var once sync.Once func GetLogger() *Logger { once.Do(func() { instance = &Logger{} }) return instance } func (l *Logger) Log(message string) { log.Println(message) }
The above are some scenarios and specific code examples suitable for applying the singleton mode in Golang. You can flexibly apply it according to project needs in actual development. Singleton mode improves code reusability and performance.
The above is the detailed content of What are the application scenarios of singleton pattern in Golang?. For more information, please follow other related articles on the PHP Chinese website!