当前位置:网站首页>Singleton mode
Singleton mode
2022-04-23 20:43:00 【baboon_ chen】
List of articles
A class can only create one object ( Or instance ), This design pattern is called singleton pattern .
The basic steps of creating a singleton :
- Constructor privatization , Avoid using external constructors to create objects .
- Add private static pointer variables (instance), This enables static member functions to access .
- Provide static public Interface , Allows the user to obtain a single instance .
One 、 Hungry Chinese style
Class is instantiated when it is defined .
#include <iostream>
using namespace std;
class Singleton {
private:
// 1、 Declare the constructor as private or protected
Singleton() {};
Singleton(const Singleton &) {};
// 2、 Declare a private static member
static Singleton *s_instance;
public:
// 3、 establish public static Method , Return instance , For external calls .
static Singleton* GetInstance();
void fun() {
cout << "call instance.\n";
}
};
// 4、 Static member initialization , Internal members can call private functions
Singleton* Singleton::s_instance = new Singleton();
Singleton* Singleton::GetInstance() {
return s_instance;
}
int main()
{
Singleton::GetInstance()->fun();
return 0;
}
advantage : Thread safety
shortcoming : Delayed loading is not supported
Two 、 Slacker type
Class instances are instantiated the first time they are used .
#include <iostream>
using namespace std;
class Singleton {
private:
// 1、 Declare the constructor as private or protected
Singleton() {};
Singleton(const Singleton &) {};
public:
// 2、 establish public static Method for external use and returns instance
static Singleton* GetInstance();
void fun() {
cout << "call instance.\n";
}
};
Singleton* Singleton::GetInstance() {
// 3、 Declare local static variables , Initialize... On the first call , When the program ends, it will automatically recycle .
static Singleton instance;
return &instance;
}
int main()
{
Singleton::GetInstance()->fun();
return 0;
}
advantage : Supports delayed loading 、 Thread safety ,《Effective C++》 Recommended approach
shortcoming : If you change the role of multi-threaded locking mode , Frequent call locking 、 Releasing locks creates performance bottlenecks .
3、 ... and 、 Double detection
as long as instance After being created , Call again getInstance() Function will not enter the lock logic . therefore , This implementation solves the problem of low concurrency of lazy type .
#include <iostream>
#include <mutex>
using namespace std;
class Singleton {
private:
// 1、 Declare the constructor as private or protected
Singleton() {};
Singleton(const Singleton &) {};
// 2、 Must be declared as a static member , Can be accessed by static member functions .
static Singleton *s_instance;
static mutex s_mutex;
public:
// 3、 Create instance return method , For external calls .
static Singleton* GetInstance();
void fun() {
cout << "call instance.\n";
}
};
// 4、 Static member variables of a class must be initialized ( Allocate memory )
// Static member variables are simply declared in a class , No definition , So define outside the class , It's actually allocating memory to static member variables
Singleton* Singleton::s_instance = nullptr;
mutex Singleton::s_mutex;
Singleton* Singleton::GetInstance() {
if (s_instance == nullptr) { // The first inspection
lock_guard<mutex> guard(s_mutex);
if (s_instance == nullptr) { // A second check
s_instance = new Singleton();
}
}
return s_instance;
}
int main()
{
Singleton::GetInstance()->fun();
return 0;
}
advantage : Supports delayed loading 、 Support single instance implementation with high concurrency .
shortcoming : Double check lock , Due to memory read and write reoder Cause insecurity .
Four 、 Example of packing sheet with template
template<typename T>
class Singleton
{
public:
static T& getInstance() {
static T value_; // Static local variables
return value_;
}
private:
Singleton();
~Singleton();
Singleton(const Singleton&); // copy constructor
Singleton& operator=(const Singleton&); // = Operator overloading
};
class A{
public:
A(){
a = 1;
}
void func(){
cout << "A.a = " << a << endl;
}
private:
int a;
};
int main()
{
Singleton<A>::getInstance().func();
return 0;
}
版权声明
本文为[baboon_ chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210546351073.html
边栏推荐
- Case of the third day of go language development fresh every day project - news release system II
- The ODB model calculates the data and outputs it to excel
- LeetCode-279-完全平方数
- 一. js的深拷贝和浅拷贝
- Bash script learning -- for loop traversal
- Experience of mathematical modeling in 18 year research competition
- 100天拿下11K,转岗测试的超全学习指南
- Psychological formula for converting RGB to gray value
- Matlab matrix index problem
- Parsing methods of JSON data in C - jar and jobobject: error reading jar from jsonreader Current JsonReader item
猜你喜欢
GO語言開發天天生鮮項目第三天 案例-新聞發布系統二
MySQL基础之写表(创建表)
Scrapy教程 - (2)寫一個簡單爬蟲
Vulnhub DC: 1 penetration notes
[SQL] string series 2: split a string into multiple lines according to specific characters
【栈和队列专题】—— 滑动窗口
2022dasctf APR x fat epidemic prevention challenge crypto easy_ real
Latest investigation and progress of building intelligence based on sati
Rt-1052 learning notes - GPIO architecture analysis
LeetCode 116. Populate the next right node pointer for each node
随机推荐
Leetcode 1337. Row K with the weakest combat effectiveness in the matrix
【PTA】L1-002 打印沙漏
The problem of 1 pixel border on the mobile terminal
How to do after winning the new debt? Is it safe to open an account online
bounding box iou
Cmake project under vs2019: calculating binocular parallax using elas method
启牛学堂有用吗,推荐的证券账户是否安全
Case of the third day of go language development fresh every day project - news release system II
【PTA】L1-006 连续因子
浅谈数据库设计之三大范式
Flex layout
Experience of mathematical modeling in 18 year research competition
bounding box iou
How can matlab obtain the truncated image in trainingimagelabeler
[stack and queue topics] - sliding window
MySQL进阶之表的增删改查
Plato Farm元宇宙IEO上线四大,链上交易颇高
Create vs project with MATLAB
Imitation Baidu map realizes the three buttons to switch the map mode by automatically shrinking the bottom
A useless confession artifact