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中的单例模式 就我本身理解而言,我认为的单例:单例在整个工程中,就相当于一个全局变量,就是不论在哪里需要用到这个类的实例变量,都可以通过单例方法来取得,而且一旦你创建了一个单例类,不论你 ...
随机推荐
- javascript学习总结之对象的深拷贝和浅拷贝
前言 最近在写ES6的文章的时候发现重复遇到关于javascript深拷贝和浅拷贝的问题,然后查找了一些资料,根据资料和自己的理解做了以下笔记,毕竟javascript关于深拷贝和浅拷贝的问题在一些面 ...
- JavaScript如何工作:垃圾回收机制 + 常见的4种内存泄漏
原文地址: How JavaScript works: memory management + how to handle 4 common memory leaks 本文永久链接:https://d ...
- Centos 新建用户
Centos 新建用户 为什么要新建用户? 因为root的权限太多,不方便多人多角色使用,所以添加一个用户 添加用户 新建用户 adduser '用户名' 添加用户密码 passwd '用户名' 输入 ...
- 基于Spring Boot的问答系统之一:elasticsearch 7.2的hello world入门
好久没有写代码了,最近想做一个基于spring boot + vue + elasticsearch + NLP(语义相关性)的小系统练练手,系统后面可以成为一个聊天机器人,客服系统的原型等等. 所以 ...
- day19作业
1.什么是对象?什么是类? 对象是特征和功能的结合体 类是一系列对象相同的特征和技能的集合体 2.绑定方法的有什么特点 绑定方式是由对象来调用类内部的函数,特点是会把对象当作第一个参数传入 ...
- boostrap原理.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- Flask源码分析二:路由内部实现原理
前言 Flask是目前为止我最喜欢的一个Python Web框架了,为了更好的掌握其内部实现机制,这两天准备学习下Flask的源码,将由浅入深跟大家分享下,其中Flask版本为1.1.1. 上次了解了 ...
- Apache Solr Velocity模板注入RCE漏洞复现
Apache Solr Velocity模板注入RCE漏洞复现 一.Apache Solr介绍 Solr是一个独立的企业级搜索应用服务器,它对外提供类似于web-service的API接口,用户可以通 ...
- H5与CSS3常用设置
1.设置div铺满全屏 对于一个div1,要使其属性height:100%生效,需要使其所有父元素,有确定的属性height.要铺满全屏,就是从html开始,所有的height为100%. 2.垂直居 ...
- 前端技术之:如何创建一个NodeJs命令行交互项目
方法一:通过原生的NodeJs API,方法如下: #!/usr/bin/env node # test.js var argv = process.argv; console.log(argv) ...