Golang Single-piece mode

Source: Internet
Author: User
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:

    • Some languages have no global variables;

    • A global variable cannot prevent a class from being instantiated more than once.

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




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.