Elegant implementation of Golang single-case mode

Source: Internet
Author: User

Through sync. Once instance to ensure that the do of a once instance is executed only once, regardless of whether the Func in do has multiple or one, using this feature to implement the singleton pattern in the design pattern, there is no such thing in Golang, so take the structure to test:

Type Singleton struct{}

var ins *singleton

var once sync. Once

Func getins () *singleton {

Once. Do (func () {

INS = &singleton{}

INS = new (singleton)

})

return INS

}

Sync. Once Doc:

Type Once

Once is a object that would perform exactly one action.

Type Once struct {

Contains filtered or unexported fields

}

Func (*once) do

Func (o *once) do (f func ())

Do calls the function f if and only if does is being called for the first time for this instance of Once. In other words, given

var once once

If once. Do (f) are called multiple times, only the first call would invoke F, even if f have a different value in each invocation. A new instance of Once is required for each function to execute.

Related Article

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.