本文首发于个人博客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. 【教程】基于Ubuntu系统的PyTorch虚拟环境配置

    目录 一.PyTorch虚拟环境配置 二.PyTorch虚拟环境使用 三.常用命令 Editor: Veagau Time: 2019/10/17 一.PyTorch虚拟环境配置 该部分操作均在终端( ...

  2. org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping

    配置spring+shiro时,启动tomcat报错异常 严重: Context initialization failedorg.springframework.beans.factory.Bean ...

  3. 谜一样的Java编码和Windows编码

    本文适用于Java源码用UTF-8编码,平台系统为Windows的情况 不管是maven,还是javac,你的IDE都会带上一个参数:-Dfile.encoding=UTF-8 Windows(或许W ...

  4. unity 截屏总结

    转载与https://www.cnblogs.com/MissLi/p/8005342.html 1.针对指定的相机进行截屏 此中方式要添加yield return waitfortheEndofFr ...

  5. linux sqlite安装

    wget http://www.sqlite.org/sqlite-3.6.16.tar.gz tar -zxvf sqlite-3.6.16.tar.gz  cd sqlite-3.6.16 ./c ...

  6. null与undefined的区别?

    古之立大事者,不惟有超世之才,亦必有坚忍不拔之志. ——北宋· 苏 轼<晁错论> 1.首先看一个判断题:null和undefined 是否相等     console.log(null== ...

  7. ssh WARNING:REMOTE HOST IDENTIFICATION HAS CHANGED(警告:远程主机标识已更改)

    ssh 192.168.1.88 出现以下警告: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ WARNING: REMOT ...

  8. 视口viewport与单位rem的本质

    结论: 视口viewport的设置是为了让字的显示在不同的屏幕下保持一致. 单位rem的使用是为了让页面中的布局元素的比例在不同的屏幕下显示的比例保持一致. 现象: 我们看电脑时候的网页的时候的字体大 ...

  9. 学习笔记23_AspMVC项目

    *创建AspMVC项目 (1)会自动创建App_Data文件夹,是用户不能访问和下载的.一般用户能访问那些文件夹,可以在IIS中配置. (2)App_Start文件夹,用于放置与程序有关的配置文件. ...

  10. Java零基础入门面向对象之多态

    多态: 多态的概念:一种事物的多种形态:允许不同类的对象对同一消息做出不同的响应 多态的前提:继承,重写:向上转型(父类引用指向子类对象) 多态的作用:提高代码的可用性:降低模块之间的耦合度 多态分类 ...