c++中实现单例模式singleton class
本文首发于个人博客https://kezunlin.me/post/8932eaec/,欢迎阅读!
singleton class and usage in c++.
Guide
what singleton solve?
Singletons solve one (and only one) problem.
Resource Contention.
If you have some resource that
(1) can only have a single instance, and
(2) you need to manage that single instance,
you need a singleton.
There aren't many examples. A log file is the big one. You don't want to just abandon a single log file. You want to flush, sync and close it properly. This is an example of a single shared resource that has to be managed.
It's rare that you need a singleton. The reason they're bad is that they feel like a global and they're a fully paid up member of the GoF Design Patterns book.
When you think you need a global, you're probably making a terrible design mistake.
local static object
Actually, in C++ preferred way is local static object.
singleton pure
class Singleton
{
private:
Singleton();
public:
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
};
singleton with shared_ptr
class Singleton
{
private:
Singleton();
public:
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;
static std::shared_ptr<Singleton> instance()
{
static std::shared_ptr<Singleton> s{new Singleton};
return s;
}
};
singleton usage
#define DISALLOW_COPY(TypeName) \
TypeName(const TypeName&)
#define DISALLOW_ASSIGN(TypeName) \
TypeName& operator=(const TypeName&)
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
TypeName& operator=(const TypeName&)
class CSingleton
{
public:
static CSingleton &GetInstance()
{
static CSingleton instance;
return instance;
}
void DoSomething()
{
printf("void CSingleton::DoSomething() called.\n");
}
private:
CSingleton() {};
DISALLOW_COPY_AND_ASSIGN(CSingleton);
};
// usage
CSingleton::GetInstance().DoSomething(); // OK
CSingleton& singleton = CSingleton::GetInstance(); // OK with reference
singleton.DoSomething();
CSingleton singleton = CSingleton::GetInstance(); // ERROR (copy constructor)
Example
config.h
#pragma once
class Config
{
public:
static Config& GetInstance(std::string filename="./config.ini");
~Config();
private:
Config(std::string filename);
Config(const Config& ref) {}
Config& operator =(const Config& ref) { return *this; }
};
config.cpp
#include "Config.h"
/*
static config instance will only be created once by calling Config::Config,
when program exit,static variable will be destoryed by calling Config::~Config.
*/
Config& Config::GetInstance(std::string filename)
{
static Config instance(filename);
return instance;
}
Config::Config(std::string filename)
{
std::cout << "[LOG] Config::Config count= "<<count << std::endl;
// load config from filename
// ...
}
Config::~Config()
{
std::cout << "[LOG] Config::~Config count= " << count << std::endl;
}
mysqldb.cpp
void MysqlDb::load_config(std::string filename)
{
this->mysql_connection = Config::GetInstance(filename).MYSQL_CONNECTION;
this->mysql_username = Config::GetInstance(filename).MYSQL_USERNAME;
this->mysql_password = Config::GetInstance(filename).MYSQL_PASSWORD;
this->mysql_database = Config::GetInstance(filename).MYSQL_DATABASE;
this->max_connection_pool_size = Config::GetInstance(filename).MAX_CONNECTION_POOL_SIZE;
}
Reference
- [c-singleton-vs-global-static-object](- https://stackoverflow.com/questions/1463707/c-singleton-vs-global-static-object)
- c-singleton-design-pattern
-cpp-singleton-memory-retrieve
History
- 20180122: created.
Copyright
- Post author: kezunlin
- Post link: https://kezunlin.me/post/8932eaec/
- Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.
c++中实现单例模式singleton class的更多相关文章
- Qt中实现单例模式(SingleTon),大约有3种办法
Qt中实现单例模式(SingleTon) 单例模式分为“饥汉”和“饿汉”两种版本,也正是线程安全问题使得原本简单的单例模式变得复杂.由于单例模式很常用,Boost库中有强大的泛型单例实现,我也利用Qt ...
- Java中的单例模式(Singleton Pattern in Java)
Introduction 对于系统中的某个类来说,只有一个实例是很重要的,比如只有一个timer和ID Producer.又比如在服务器程序中,配置信息保留在一个文件中,这些配置信息由一个单例对象统一 ...
- 设计模式之单例模式——Singleton
设计模式之单例模式--Singleton 设计意图: 保证类仅有一个实例,并且可以供应用程序全局使用.为了保证这一点,就需要这个类自己创建自己的对象,并且对外有 ...
- 【白话设计模式四】单例模式(Singleton)
转自:https://my.oschina.net/xianggao/blog/616385 0 系列目录 白话设计模式 工厂模式 单例模式 [白话设计模式一]简单工厂模式(Simple Factor ...
- Objective-C中的单例模式
单例模式算是设计模式中比较简单的一种吧,设计模式不是只针对某种编程语言,在C++, Java, PHP等其他OOP语言也有设计模式,笔者初接触设计模式是通过<漫谈设计模式>了解 ...
- C# 中实现单例模式
文章目录 简介 不安全线程的单例模式 简单安全线程带锁 双重检查 - 带锁 安全初始化 安全并且懒汉式静态初始化 带泛型的懒汉式单例 异常 提高效率 总结 简介 单例模式是软件工程中广为人知的设计模式 ...
- 转:C++中的单例模式
C++中的单例模式 单例模式也称为单件模式.单子模式,可能是使用最广泛的设计模式.其意图是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享.有很多地方需要这样的功能模块, ...
- ooad单例模式-Singleton
单例模式Singleton 主要作用是保证在Java应用程序中,一个类Class只有一个实例存在. 比如建立目录 ...
- 浅谈iOS中的单例模式
iOS中的单例模式 就我本身理解而言,我认为的单例:单例在整个工程中,就相当于一个全局变量,就是不论在哪里需要用到这个类的实例变量,都可以通过单例方法来取得,而且一旦你创建了一个单例类,不论你 ...
随机推荐
- openflow流表项中有关ip掩码的匹配的问题(控制器为ryu)
一.写在前面 唉,被分配到sdn安全方向,顶不住,顶不住,感觉搞不出来什么有搞头的东西.可若是让我水水的应付,我想我也是做不到的,世上无难事只怕有心人.好了,进入正题,本次要讨论的时一个比较细节的东西 ...
- day1-01 温度转换
一."温度转换"问题分析 1.1 温度转换 温度刻画的两种不同体系 摄氏度:中国等世界大多数国家使用 以1标准大气压下水的结冰点为0度,沸点为100度,将温度进行等分刻画 华氏度: ...
- 4. SOFAJRaft源码分析— RheaKV初始化做了什么?
前言 由于RheaKV要讲起来篇幅比较长,所以这里分成几个章节来讲,这一章讲一讲RheaKV初始化做了什么? 我们先来给个例子,我们从例子来讲: public static void main(fin ...
- Java socket Tcp协议 实现文件传输
1.文件加密上传后发现文件已损坏: 原因:使用 read(byte[]) 方法不能够准确的获取到正确的字节数,有可能比 byte[].length 小,所以在解密的时候出现错误. 解决办法: 判断读取 ...
- 美团 iOS 端开源框架 Graver 在动态化上的探索与实践
近些年,移动端动态化技术可谓是“百花齐放”,其中的渲染性能也是动态化技术一直在探索.研究的课题.美团的开源框架 Graver 也为解决动态化框架的渲染性能问题提供了一种新思路:关于布局,我们可以采用“ ...
- Java源码 HashMap.roundUpToPowerOf2原理
int rounded = number >= MAXIMUM_CAPACITY ? MAXIMUM_CAPACITY : (rounded = Integer.highestOneBit(nu ...
- Java基础(十九)集合(1)集合中主要接口和实现类
1.Java集合框架为不同类型的集合定义了大量接口 其中,集合有两个基本接口:Collection和Map. 2.各接口的主要特征如下 (1)Collection接口:是List接口.Set接口和Qu ...
- fenby C语言
P1框架 1#include <stdio.h> 2 3int main(){ 4 printf(“C语言我来了”); 5 return 0; 6} P2main()门 P3计 ...
- python基础-字典dict
字典-dict 用途: 定义方法:通过{} 来存储数据,通过key:value (键值对)来存储数据,每个键值对通过逗号分隔.在键值对中,key 是不可变的数据类型,value 是任意数据类型 def ...
- Java 用单向循环链表实现 约瑟夫问题
public class lianbiao2 { class Node{ Node next; int number; public Node getNext() { return next; } p ...