当前位置:网站首页>创建型模式 - 单例模式
创建型模式 - 单例模式
2022-06-21 12:00:00 【attempt_to_do】
1.模式动机
对于系统中的某些类来说,只有一个实例很重要,例如,一个系统中可以存在多个打印任务,但是只能有一个正在工作的任务;一个系统只能有一个窗口管理器或文件系统;一个系统只能有一个计时工具或ID(序号)生成器。
如何保证一个类只有一个实例并且这个实例易于被访问呢?定义一个全局变量可以确保对象随时都可以被访问,但不能防止我们实例化多个对象。
一个更好的解决办法是让类自身负责保存它的唯一实例。这个类可以保证没有其他实例被创建,并且它可以提供一个访问该实例的方法。这就是单例模式的模式动机。
2.模式定义
单例模式(Singleton Pattern):单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。
单例模式的要点有三个:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。单例模式是一种对象创建型模式。单例模式又名单件模式或单态模式。
3.模式结构

4.时序图

5.代码分析
5.1.c++实现
#include "Singleton.h"
#include <iostream>
using namespace std;
Singleton * Singleton::instance = NULL;
Singleton::Singleton(){
}
Singleton::~Singleton(){
delete instance;
}
Singleton* Singleton::getInstance(){
if (instance == NULL)
{
instance = new Singleton();
}
return instance;
}
void Singleton::singletonOperation(){
cout << "singletonOperation" << endl;
}
#include <iostream>
#include "Singleton.h"
using namespace std;
int main(int argc, char *argv[])
{
Singleton * sg = Singleton::getInstance();
sg->singletonOperation();
return 0;
}
5.2.Golang实现
package singleton
type singleton map[string]string
var (
once sync.Once
instance singleton
)
func New() singleton {
once.Do(func() {
instance = make(singleton)
})
return instance
}
s := singleton.New()
s["this"] = "that"
s2 := singleton.New()
fmt.Println("This is ", s2["this"])
// This is that
6.模式分析
单例模式的目的是保证一个类仅有一个实例,并提供一个访问它的全局访问点。单例模式包含的角色只有一个,就是单例类——Singleton。单例类拥有一个私有构造函数,确保用户无法通过new关键字直接实例化它。除此之外,该模式中包含一个静态私有成员变量与静态公有的工厂方法,该工厂方法负责检验实例的存在性并实例化自己,然后存储在静态成员变量中,以确保只有一个实例被创建。
在单例模式的实现过程中,需要注意如下三点:
- 单例类的构造函数为私有;
- 提供一个自身的静态私有成员变量;
- 提供一个公有的静态工厂方法。
7.适用环境
在以下情况下可以使用单例模式:
- 系统只需要一个实例对象,如系统要求提供一个唯一的序列号生成器,或者需要考虑资源消耗太大而只允许创建一个对象。
- 客户调用类的单个实例只允许使用一个公共访问点,除了该公共访问点,不能通过其他途径访问该实例。
- 在一个系统中要求一个类只有一个实例时才应当使用单例模式。反过来,如果一个类可以有几个实例共存,就需要对单例模式进行改进,使之成为多例模式
边栏推荐
- Snow Ice City (blackened)
- tensorflow中使用的一些函数
- 矩形覆盖面积
- harmonyos培训一
- The final battle of the giant: instant retailing
- Is it safe to hit new bonds with one click? Is it reliable?
- Tensorflower使用指定的GPU和GPU显存
- A recovery solution of system paralysis caused by upgrading glibc of VMware virtual machine
- These three young men are more ruthless than Ma Huateng and Zhang Yiming
- PCB电路板设计都有哪些注意事项?
猜你喜欢

2-zabbix使用自动发现自动添加主机
![[deep learning] use deep learning to monitor your girlfriend's wechat chat?](/img/03/ecf50eacc91c0633b0d9689cdad2c2.png)
[deep learning] use deep learning to monitor your girlfriend's wechat chat?

Apache ShardingSphere 5.1.2 发布|全新驱动 API + 云原生部署,打造高性能数据网关

Interesting research on mouse pointer interaction

Introduction to common source oscilloscope software and RIGOL oscilloscope upper computer software ns-scope

2022 safety officer-c certificate title and answer

Snow Ice City (blackened)

Jenkins 通过Build periodically配置定时任务

Formation harmonyos I

Customization of power aging test system | overview of charging pile automatic test system nsat-8000
随机推荐
Quantitative research on heterogeneous communities 4 rate of change with bands
findpanel的相关代码
A Kuan food: the battle for "the first share of convenience food" continues
Hands on data analysis data visualization
Harmonyos training I
一文搞懂 Flink OperatorChain 对象重用
旅行不能治愈心灵
[yolov5s target detection] opencv loads onnx model for reasoning on GPU
HMS Core机器学习服务身份证识别功能,实现信息高效录入
harmonyos培訓一
Jenkins configures scheduled tasks through build periodically
Sdcc compiler + vscode to develop 8-bit microcontroller
ACM. HJ36 字符串加密 ●●
harmonyos培训一
MySQL-DQL
Apache ShardingSphere 5.1.2 发布|全新驱动 API + 云原生部署,打造高性能数据网关
Clear the switch configuration, configure the image port and Wireshark packet capturing (take Huawei s5720 as an example)
【云原生 | Devops篇】Jenkins安装与实战(二)
I would like to ask you guys, the flick CDC will add a table level exclusive lock before extracting the full amount of Oracle data
Tensorflower uses the specified GPU and GPU video memory