This is a creation in Article, where the information may have evolved or changed.
Single-piece mode singleton
It is to provide a global instance. For example, a database connection, if each user and thread are applied independently, it will soon reach the upper limit of the database connection. The global variable is not used because:
The ultimate goal is to ensure that only one global instance is available, such as through the conventional Instance (), and Instance () guarantees that it will not be created repeatedly. Or you cannot invoke the constructor of the class, but only the get instance function of the class, which makes it impossible to create a new instance.
---
Directory structure
Main.go
./singleton/singleton.go
Singleton.go
Package Singletonimport ("FMT") var _self *singletontype Singleton struct {Name string}func Instance () *singleton {if _self = = Nil {_self = new (Singleton) return _self}return _self}func (o *singleton) SetName (s string) {_self. Name = S}func (o *singleton) GetName () {fmt. Println ("Name:", _self. Name)}
Main.go
Package Mainimport ("./singleton") func main () {a: = Singleton. Instance () B: = Singleton. Instance () a.setname ("Funny") b.setname ("Test") A.getname () return}
Results: Name:test