当前位置:网站首页>Design pattern singleton (go language)

Design pattern singleton (go language)

2020-12-06 21:23:36 Cucumber and potato

1. The singleton pattern

Make sure there is only one instance of a class , And provide a global access point to access it . There are two ways to achieve :sync.Mutex And the structure sync.Once.sync.Once, It has one Do Method , Its function in go Only one call is guaranteed !

2. Example

package singleton

import "sync"
// Use structs instead of classes 
type Instance struct {
	Name string
}
var (
	goInstance *Instance
	once       sync.Once
)

//  Use go  Implement singleton mode , Hungry Chinese style -- Global variable creation 
func GoInstance(name string) *Instance {
	if goInstance == nil {
		// adopt  sync.Once  To ensure that the object creation method is executed only once ---- It has the effect of double checking ,sync.Once Internal encapsulated judgment 
		once.Do(func() {
			goInstance = &Instance{
				Name: name,
			}
		})
	}
	return goInstance
}
package singleton

import "sync"

// Traditional way to implement singleton pattern 
var (
	instance *Instance
	lock     sync.Mutex
)
//Instance Definition   stay go_singleton.go
//type Instance struct {
//	Name string
//}

//  Double check 
func GetInstance(name string) *Instance {
	if instance == nil {
		lock.Lock()
		defer lock.Unlock()
		if instance == nil {
			instance = &Instance{Name: name}
		}
	}
	return instance
}
package singleton

import "testing"

// Go Language patterns 
func TestGoSingleton(t *testing.T) {
	instance1 := GoInstance("test")
	// View its memory address 
	t.Logf("%p", instance1)

	instance2 := GoInstance("test")
	t.Logf("%p", instance2)
}

//  The traditional model 
func TestSingleton(t *testing.T) {
	instance1 := GetInstance("test")
	// View its memory address 
	t.Logf("%p", instance1)

	instance2 := GetInstance("test")
	t.Logf("%p", instance2)
}

 

 

 

 

 

版权声明
本文为[Cucumber and potato]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201206212224737e.html