2.1 设计模式

Go 设计模式#

单例模式#

常规#

package singleton
import "sync"

var (
    instance *Instance
    lock     sync.Mutex
)

type Instance struct {
    Name string
}

// 双重检查
func GetInstance(name string) *Instance {
    if instance == nil {
        lock.Lock()
        defer lock.Unlock()
        if instance == nil {
            instance = &Instance{Name: name}
        }
    }
    return instance
}

sync.Once#

package singleton

import "sync"

var (
    goInstance *Instance
    once       sync.Once
)

func GoInstance(name string) *Instance {
    if goInstance == nil {
        once.Do(func() {
            goInstance = &Instance{
                Name: name,
            }
        })
    }
    return goInstance
}

参考#

tmrts/go-patterns Github stars#

senghoo/golang-design-pattern Github stars Language Last Tag Last commit#