本文首发于个人博客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

History

  • 20180122: created.

Copyright

c++中实现单例模式singleton class的更多相关文章

  1. Qt中实现单例模式(SingleTon),大约有3种办法

    Qt中实现单例模式(SingleTon) 单例模式分为“饥汉”和“饿汉”两种版本,也正是线程安全问题使得原本简单的单例模式变得复杂.由于单例模式很常用,Boost库中有强大的泛型单例实现,我也利用Qt ...

  2. Java中的单例模式(Singleton Pattern in Java)

    Introduction 对于系统中的某个类来说,只有一个实例是很重要的,比如只有一个timer和ID Producer.又比如在服务器程序中,配置信息保留在一个文件中,这些配置信息由一个单例对象统一 ...

  3. 设计模式之单例模式——Singleton

                        设计模式之单例模式--Singleton 设计意图: 保证类仅有一个实例,并且可以供应用程序全局使用.为了保证这一点,就需要这个类自己创建自己的对象,并且对外有 ...

  4. 【白话设计模式四】单例模式(Singleton)

    转自:https://my.oschina.net/xianggao/blog/616385 0 系列目录 白话设计模式 工厂模式 单例模式 [白话设计模式一]简单工厂模式(Simple Factor ...

  5. Objective-C中的单例模式

    ​    ​单例模式算是设计模式中比较简单的一种吧,设计模式不是只针对某种编程语言,在C++, Java, PHP等其他OOP语言也有设计模式,笔者初接触设计模式是通过<漫谈设计模式>了解 ...

  6. C# 中实现单例模式

    文章目录 简介 不安全线程的单例模式 简单安全线程带锁 双重检查 - 带锁 安全初始化 安全并且懒汉式静态初始化 带泛型的懒汉式单例 异常 提高效率 总结 简介 单例模式是软件工程中广为人知的设计模式 ...

  7. 转:C++中的单例模式

    C++中的单例模式 单例模式也称为单件模式.单子模式,可能是使用最广泛的设计模式.其意图是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享.有很多地方需要这样的功能模块, ...

  8. ooad单例模式-Singleton

                                                单例模式Singleton 主要作用是保证在Java应用程序中,一个类Class只有一个实例存在. 比如建立目录 ...

  9. 浅谈iOS中的单例模式

    iOS中的单例模式     就我本身理解而言,我认为的单例:单例在整个工程中,就相当于一个全局变量,就是不论在哪里需要用到这个类的实例变量,都可以通过单例方法来取得,而且一旦你创建了一个单例类,不论你 ...

随机推荐

  1. LeetCode刷题笔记(2)HashMap相关应用

    1.问题描述 Example 1: Input: A = "this apple is sweet", B = "this apple is sour" Out ...

  2. python dict(字典)

    补充知识点1: 数据类型的划分:可变数据类型.不可变数据类型 可变数据类型:     元组,bool,int,str      --可哈希 不可变数据类型:  list,dict,set        ...

  3. VSCode实现文献管理

    1 常用文献管理软件 常用的文献管理软件有mendely,zotero,endnote和Papers(需要付费),具体对比参考链接1.1.1.2 笔者只用过Mendely,当时综合考虑挑了Endnot ...

  4. [UWP] 为WinRT组件创建Nuget包

    Nuget 是 dotnet 开发中必不可少的包管理工具,但不仅仅局限于 dotnet 项目,在 VS 中使用 C++ 开发的时候,也可以使用 Nuget 来引用第三方组件.同样也可以用 Nuget ...

  5. Lab_1:练习3——分析bootloader进入保护模式的过程

    文章链接:https://www.cnblogs.com/cyx-b/p/11809742.html 作者:chuyaoxin 一.实验内容 BIOS将通过读取硬盘主引导扇区到内存,并转跳到对应内存中 ...

  6. MongoDB的基础命令

    MongoDB的介绍 MongoDB: 是一个基于bson(二进制json)的NoSQL数据库 MongoDB的三要素: 数据库: 类似于MYSQL的数据库 集合: 类似于MYSQL的表 文档: 类似 ...

  7. JDBC报错:The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone

    报错原因:查阅资料发现这都是因为安装mysql的时候时区设置的不正确 mysql默认的是美国的时区,而我们中国大陆要比他们迟8小时,采用+8:00格式 解决方法: 1.修改MySQL的配置文件,MyS ...

  8. markdown 编辑器概述

    markdown 编辑器概述     编辑器其实很多很多,主要分为    网页编辑和软件编辑 (效果其实感觉效果差不多,看个人喜好,笔者个人还是喜欢本地,感觉方便挺多的) ## 网页编辑器 主要有 C ...

  9. DHCP动态管理主机地址

    步骤一:搭建环境 需要Windows 2008 R2 系统  (DHCP服务端)以及 CentOS7 系统客户机(DHCP客户机) 安装DHCP服务程序(这里提示读者,一般安装好CentOS系统之后, ...

  10. 二叉搜索树BST(C语言实现可用)

    1:概述 搜索树是一种可以进行插入,搜索,删除等操作的数据结构,可以用作字典或优先级队列.二叉搜索树是最简单的搜索树.其左子树的键值<=根节点的键值,右子树的键值>=根节点的键值. 如果共 ...