单例模式
此为《剑指offer》中的面试题二,本文用 go 语言实现;
一、问题
设计一个类,我们只能生成该类的一个实例。
二、分析
单例模式
定义:“一个类有且仅有一个实例,并且自行实例化向整个系统提供。”
特点:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一实例。
- 单例类必须给所有其他对象提供这一实例。
要解决的问题:避免一个全局使用的类频繁地创建与销毁;保证一个类仅有一个实例,并提供一个访问它的全局访问点。
在 go 语言中,主要的实现方式有以下四种:
- 懒汉式:线程(不)安全,需要实例的时候才会主动去创建实例,并且可以通过 Sync.Mutex 加锁来实现线程安全。
- 饿汉式:线程安全,导入包的同时会创建实例,持续占用内存。
- 双重检查:线程安全,在懒汉式(线程安全)的基础上再进行忧化,在未创建实例的时候才会加锁。保证线程安全同时不影响性能。
- sync.Once:通过 sync.Once 来确保创建对象的方法只执行一次,Once 内部也是实现的双重检查。
三、实现
package Singleton
import "sync"
var once sync.Once
var lock sync.Mutex
type Instance struct {
email string
}
// 私有的实例指针
var instance *Instance
// 利用 sync.Once 实现
func GetInstance() *Instance {
once.Do(func() {
instance = new(Instance)
})
return instance
}
// 懒汉式,非线程安全
func GetInstance1() *Instance {
if instance == nil {
instance = new(Instance)
}
return instance
}
// 懒汉式,线程安全
func GetInstance2() *Instance {
lock.Lock()
defer lock.Unlock()
if instance == nil {
instance = new(Instance)
}
return instance
}
// 私有的实例
var instance1 Instance
// 饿汉式,线程安全
func GetInstance3() *Instance {
return &instance1
}
// 双重检查
func GetInstance4() *Instance {
if instance == nil {
lock.Lock()
if instance == nil {
instance = new(Instance)
}
lock.Unlock()
}
return instance
}
// 这是 once.go 在 1.13.1 中的实现,可以看到也是使用 双重检查 的方式。
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sync
import (
"sync/atomic"
)
// Once is an object that will perform exactly one action.
type Once struct {
// done indicates whether the action has been performed.
// It is first in the struct because it is used in the hot path.
// The hot path is inlined at every call site.
// Placing done first allows more compact instructions on some architectures (amd64/x86),
// and fewer instructions (to calculate offset) on other architectures.
done uint32
m Mutex
}
// Do calls the function f if and only if Do is being called for the
// first time for this instance of Once. In other words, given
// var once Once
// if once.Do(f) is called multiple times, only the first call will invoke f,
// even if f has a different value in each invocation. A new instance of
// Once is required for each function to execute.
//
// Do is intended for initialization that must be run exactly once. Since f
// is niladic, it may be necessary to use a function literal to capture the
// arguments to a function to be invoked by Do:
// config.once.Do(func() { config.init(filename) })
//
// Because no call to Do returns until the one call to f returns, if f causes
// Do to be called, it will deadlock.
//
// If f panics, Do considers it to have returned; future calls of Do return
// without calling f.
//
func (o *Once) Do(f func()) {
// Note: Here is an incorrect implementation of Do:
//
// if atomic.CompareAndSwapUint32(&o.done, 0, 1) {
// f()
// }
//
// Do guarantees that when it returns, f has finished.
// This implementation would not implement that guarantee:
// given two simultaneous calls, the winner of the cas would
// call f, and the second would return immediately, without
// waiting for the first's call to f to complete.
// This is why the slow path falls back to a mutex, and why
// the atomic.StoreUint32 must be delayed until after f returns.
if atomic.LoadUint32(&o.done) == 0 {
// Outlined slow-path to allow inlining of the fast-path.
o.doSlow(f)
}
}
func (o *Once) doSlow(f func()) {
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}
四、总结
单例模式是最简单的一种设计模式,也是面试中常问到的题目;在不同编程语言中,可以结合语言的特性,给出不同的实现方式。可以结合具体的编程语言,思考一下面试官 care 的考点在哪里。
比如:执行效率、线程安全、代码风格、充分利用语言特性…
——2019-10-07——