[go] 单例模式

单例模式

确保类只有一个实例,并提供一个全局的访问点。

  • 单例(Singleton)类声明了一个名为getInstance的方法来返回其所属类的一个相同实例。

  • 单例的构造函数必须对客户端的代码隐藏。调用getInstance方法必须是获取单例对象的唯一方式。

优缺点

1.优点

你可以肯定,一个类只有一个实例。

有助于获得该实例的全局访问点。

仅在首次请求单例对象时对其进行初始化。

2.缺点

  • 它违反了单一责任原则。该模式同时解决了两个问题。
  1. 保证一个类只有一个实例
  2. 为该实例提供一个全局访问节点
  • 单例模式可以掩盖糟糕的设计。例如,当程序组件对彼此了解太多。

  • 不是线程安全的,你写的代码要确保为所有线程只创建一个实例。

  • 单例的客户端代码单元测试可能会比较困难, 因为许多测试框架以基于继承的方式创建模拟对象。 由于单例类的构造函数是私有的, 而且绝大部分语言无法重写静态方法, 所以你需要想出仔细考虑模拟单例的方法。 要么干脆不编写测试代码, 或者不使用单例模式。

使用场景

  • 如果程序中的某个类对于所有客户端只有一个可用的实例, 可以使用单例模式。
  • 如果你需要更加严格地控制全局变量, 可以使用单例模式。

参考代码

这里我们分两个例子吧,一个是简单的单例实现,另外一个是解决异步情况可能会出现的问题
sample

go 复制代码
type single struct{}

var normalSingleInstance *single

func getNormalSingle() *single {
	if normalSingleInstance == nil {
		fmt.Println("creating single instance")
		normalSingleInstance = new(single)
	} else {
		fmt.Println("single instance already created")
	}
	return normalSingleInstance
}

func main() {
	for i := 0; i < 10; i++ {
		getNormalSingle()
	}
}

输出:

go 复制代码
creating single instance
single instance already created
single instance already created
single instance already created
single instance already created
single instance already created
single instance already created
single instance already created
single instance already created
single instance already created

multithread

go 复制代码
type single struct{}

var lock = &sync.Mutex{}

var multiThreadSafeInstance *single

func getMultiThreadSafeInstance() *single {
	if multiThreadSafeInstance == nil {
		lock.Lock()
		defer lock.Unlock()
		if multiThreadSafeInstance == nil {
			fmt.Println("creating multi-thread safe instance now.")
			multiThreadSafeInstance = new(single)
		} else {
			fmt.Println("multi-thread safe instance already created.")
		}
	} else {
		fmt.Println("multi-thread safe instance already created.")
	}

	return multiThreadSafeInstance
}

func main() {
	for i := 0; i < 2; i++ {
		go func() {
			for j := 0; j < 5; j++ {
				getMultiThreadSafeInstance()
			}
		}()
	}
	select {}
}

输出:

go 复制代码
creating multi-thread safe instance now. 
multi-thread safe instance already created. 
multi-thread safe instance already created. 
multi-thread safe instance already created. 
multi-thread safe instance already created. 
multi-thread safe instance already created. 
multi-thread safe instance already created. 
multi-thread safe instance already created. 
multi-thread safe instance already created. 
multi-thread safe instance already created.
相关推荐
像风一样自由20201 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
浪裡遊2 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
简佐义的博客4 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
Liudef064 小时前
2048小游戏实现
javascript·css·css3
独立开阀者_FwtCoder6 小时前
【Augment】 Augment技巧之 Rewrite Prompt(重写提示) 有神奇的魔法
前端·javascript·github
我想说一句6 小时前
事件机制与委托:从冒泡捕获到高效编程的奇妙之旅
前端·javascript
汤姆Tom6 小时前
JavaScript reduce()函数详解
javascript
小飞悟6 小时前
你以为 React 的事件很简单?错了,它暗藏玄机!
前端·javascript·面试
中微子6 小时前
JavaScript 事件机制:捕获、冒泡与事件委托详解
前端·javascript