Golang单例模式

101 阅读1分钟

相关repo: gitee.com/gaaidou/gaa…

1.Golang的Once模式创建单例。 2.懒汉式,兼容线程安全 3.饿汉式

singleton.go

package designpattern

import (
	"sync"
	"time"
)

type Singleton struct {
	CurrTime time.Time
}

var once sync.Once
var onceInstance *Singleton

func OnceFunc() *Singleton {
	once.Do(func() {
		onceInstance = &Singleton{CurrTime: time.Now()}
	})
	return onceInstance
}

var lazyInstance *Singleton
var lock sync.Mutex

func LazyFunc() *Singleton {
	if lazyInstance == nil {
		lock.Lock()
		if lazyInstance == nil {
			lazyInstance = &Singleton{CurrTime: time.Now()}
		}
		lock.Unlock()
	}

	return lazyInstance
}

var hungryInstance = &Singleton{CurrTime: time.Now()}

func HungryFunc() *Singleton {
	return hungryInstance
}

singleton_test.go

package design_pattern

import (
	"ptarmigan-golang-design-pattern/src/designpattern"
	"testing"
	"time"
)

func TestOnce(t *testing.T) {

	obj1 := designpattern.OnceFunc()
	time.Sleep(time.Second * 10)
	obj2 := designpattern.OnceFunc()
	if obj1.CurrTime != obj2.CurrTime {
		t.Error("There aren't same Object")
	}
	println("Create OnceFunc Singleton Successfully")
}

func TestLazy(t *testing.T) {
	obj1 := designpattern.LazyFunc()
	time.Sleep(time.Second * 10)
	obj2 := designpattern.LazyFunc()
	if obj1.CurrTime != obj2.CurrTime {
		t.Error("There aren't same Object")
	}
	println("Create Lazy Singleton Successfully")
}

func TestHungry(t *testing.T) {
	obj1 := designpattern.HungryFunc()
	time.Sleep(time.Second * 10)
	obj2 := designpattern.HungryFunc()
	if obj1.CurrTime != obj2.CurrTime {
		t.Error("There aren't same Object")
	}
	println("Create Hungry Singleton Successfully")
}