本文首发于个人博客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. 是可忍孰不可忍!!nodepad++作者台独分子,恶毒言论!!!

    本来用了两年这个软件吧,不带任何情感的,单纯辅助工具.直到今天,在GitHub上,发现了这个作者以及一些同党都是一群尼玛生在中国骂中国的狗币. https://github.com/notepad-p ...

  2. 设置H5页面文字不可复制

    * { moz-user-select: -moz-none; -moz-user-select: none; -o-user-select: none; -khtml-user-select: no ...

  3. react框架安装和使用

    react 其实react跟vue差不多, 区别:vue-  双向数据绑定, react  单向数据绑定. 中文文档:https://react.docschina.org/ 第一步:安装方式,不能直 ...

  4. Django配置实现数据库读写分离

    django在进行数据库操作的时候,读取数据与写数据(增.删.改)可以分别从不同的数据库进行操作. 1. 在配置文件中增加slave数据库的配置 2. 创建数据库操作的路由分发类 在meiduo_ma ...

  5. 面经-科大讯飞AI研究院

    面试时间:2019.06.27 电话面试 面试岗位:计算机视觉算法工程师/一面 面试时长:45分钟 面试内容: 自我介绍 简历中选择一个项目介绍-视频召回 问及项目中的语音.人脸.标题.模态缺失相关细 ...

  6. Spring Cloud gateway 三 自定义过滤器GatewayFilter

    之前zuul 网关介绍.他有过滤器周期是四种,也是四种类型的过滤器.而gateway 只有俩种过滤器:"pre" 和 "post". PRE: 这种过滤器在请求 ...

  7. [考试反思]1018csp-s模拟测试78(lrd day2) :规律

    zkt没素质果然考炸了! 但是他考炸了和我一个分 这场的状态是真的不好,T3比较简单但没有做,一直干T2结果还是跪了 T1的哈希写挂了,模数比int大了结果一乘就炸long long了. 调了一个小时 ...

  8. [考试反思]0914csp-s模拟测试43:破绽

    T1会正解.爆int了,代码里一大堆long long但是有一个地方落了.-70分. 离考试结束还有19秒的时候发现手模样例爆负数了,没来得及改. T2没想.打暴力了.然而实际很好想...早读5分钟就 ...

  9. 7.25 NOIP模拟8

    这次考试前面状态还行,后两个小时真是一言难尽,打了个T3的n^2暴力就懵逼了,不知道怎么优化. T1.匹配 看了一边题发现不太懂(这不是考试的难度啊),然后水完T2后回来5分钟水过,非常愉快的一道题. ...

  10. SSM配置后可以访问静态html文件但无法访问其他后台接口的解决方案

    web.xml中的一段 <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class> ...