Singleton

Sometimes, you may come across a need to restrict the number of objects of a specific time in the system. Singleton is the design pattern that restricts the creation of objects to a single one. This might be useful, for example, when you want a single coordinator object across in multiple places of the code.

The following code snippet shows how to implement the singleton pattern in Go. Note that we have used the sync.Do() method: if once.Do(f) is called multiple times, only the first call will invoke the function f, even in the face of multiple threads calling this simultaneously:


type MyClass struct {
attrib string
}

func (c* MyClass ) SetAttrib(val string) {
c.attrib = val
}

func (c* MyClass ) GetAttrib() string {
return c.attrib
}

var (
once sync.Once
instance *MyClass
)

func GetMyClass() *MyClass {
once.Do(func() {
instance = &MyClass{"first"}
})

return instance
}

It can be used as follows:

a:= GetMyClass()
a.SetAttrib("second")
fmt.Println(a.GetAttrib()) // will print second
b:= GetMyClass()
fmt.Println(b.GetAttrib()) // will also print second
It should be noted that the singleton pattern is actually considered an anti-pattern because of the introduction of a global state. This causes a hidden coupling between components and can lead to difficult-to-debug situations. It should not be overused.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset