当前位置:网站首页>创建型模式 - 单例模式
创建型模式 - 单例模式
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.适用环境
在以下情况下可以使用单例模式:
- 系统只需要一个实例对象,如系统要求提供一个唯一的序列号生成器,或者需要考虑资源消耗太大而只允许创建一个对象。
- 客户调用类的单个实例只允许使用一个公共访问点,除了该公共访问点,不能通过其他途径访问该实例。
- 在一个系统中要求一个类只有一个实例时才应当使用单例模式。反过来,如果一个类可以有几个实例共存,就需要对单例模式进行改进,使之成为多例模式
边栏推荐
- Is 100W data table faster than 1000W data table query?
- 记一次Vmware虚拟机升级GLIBC导致系统瘫痪的恢复解决方法
- 知识点:PCB电路板的几种特殊布线方法
- How does Huawei build a project centered project management system from 0 to 1?
- Use huggingface to quickly load pre training models and datasets in the moment pool cloud
- Introduction to the upper computer software ns-scope of Tektronix oscilloscope
- [yolov5s target detection] opencv loads onnx model for reasoning on GPU
- CPU、MPU、MCU、SoC、MCM介绍
- 1108. IP 地址无效化
- Apache ShardingSphere 5.1.2 发布|全新驱动 API + 云原生部署,打造高性能数据网关
猜你喜欢

Is 100W data table faster than 1000W data table query?

2022 special operation certificate examination question bank and online simulation examination for safety management personnel of hazardous chemical business units

2-zabbix automatically add hosts using autodiscover

Jenkins 通过Build periodically配置定时任务

Musk's "good friend" impacts the largest IPO of Hong Kong stocks in 2022

MySQL 5.6.49 enterprise version setting password complexity policy

Sdcc compiler + vscode to develop 8-bit microcontroller

XML实体注入漏洞

泰克Tektronix示波器上位机软件NS-Scope介绍

电源老化测试系统定制|充电桩自动化测试系统NSAT-8000概述
随机推荐
SSD [target detection]
i.MX - RT1052 脉宽调制(PWM)
Brief discussion on four full bonding processes of oca\uv-oca loca\sloca
Est le logiciel d'oscilloscope allemand, le logiciel d'ordinateur hôte d'oscilloscope keysight NS scope
Travel does not heal the soul
Hands on data analysis data visualization
Golang implements redis (9): use geohash to search people nearby
2022 safety officer-b certificate retraining question bank and simulated examination
20n10-asemi medium and low voltage MOS tube 20n10
Shell process control - 35. Multi branch case conditional statements
Tensorflower uses the specified GPU and GPU video memory
Factory mode implementation
2022 HV electrician judgment questions and answers
What are the precautions for PCB design?
SSD的anchor_box计算
【无标题】
[comprehensive pen test] sword finger offer II 114 Alien dictionary
ACM. HJ36 字符串加密 ●●
Vs code + GCC environment compilation for STM32 development
旅行不能治愈心灵