单例模式(C++实现)
1、
单例模式:保证⼀个类只有⼀个对象实例,并提供⼀个访问该对象实例的全局访问点。
单例模式有两种实现⽅法:懒汉模式和饿汉模式。
2、饿汉模式
就是说不管你将来⽤不⽤,程序启动时就创建⼀个唯⼀的实例对象。
优点:简单。
缺点:可能会导致进程启动慢,且如果有多个单例类对象实例启动顺序不确定。
在访问的线程⽐较多时,采⽤饿汉模式,可以实现更好的性能,这⾥是以空间换时间。饿汉模式线程是安全的,因为⼀开始已经对单例类进⾏的实例化。
3、懒汉模式
如果单例对象构造⼗分耗时或者占⽤很多资源,⽐如加载插件啊, 初始化⽹络连接啊,读取⽂件啊等 等,⽽有可能该对象程序运⾏时不会⽤到,那么也要在程序⼀开始就进⾏初始化,就会导致程序启动时 ⾮常的缓慢。 所以这种情况使⽤懒汉模式(延迟加载)更好。优点:第⼀次使⽤实例对象时,创建对象。进程启动⽆负载。多个单例实例启动顺序⾃由控制。
缺点:复杂。#include <iostream>class Singleton{public: static Singleton* getInstance() { return &_sin; }private: //构造函数私有 Singleton(){} //防拷贝 /*Singleton(const Singleton& s);*/ /*Singleton(const Singleton& s) = delete;*/ //禁⽌赋值 Singleton& operator=(const Singleton& s); static Singleton _sin;};Singleton Singleton::_sin;int main(){ Singleton* ps = Singleton::getInstance(); /*Singleton s(*ps);*/ Singleton* ps2 = Singleton::getInstance(); return 0;}
12
3
4
5
6
7
8
单例模式的几种实现方式9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25#include <iostream>#include <thread>#include <mutex>using namespace std;class Singleton{public: static Singleton* getIntance(){ if (_ps == nullptr){ _mtx.lock(); if (_ps == nullptr){ _ps = new Singleton; } _mtx.unlock();
1
2
3
4
5
6
7
8
9
10
11
12
13
} return _ps; } //~Singleton(){ // if (_ps){ // //⽆线递归,导致栈溢出 // delete _ps; // _ps = nullptr; // } //} ~Singleton(){ cout << "~Singleton()" << endl; } class GC{ public: ~GC(){ if (_ps){ delete _ps; _ps = nullptr; } } };protected: Singleton(){ for (int i = 0; i < 10000000; i++){ int b = i; } }private: Singleton(const Singleton& s); static Singleton* _ps; static mutex _mtx; static GC _gc;};Singleton* Singleton::_ps = nullptr;mutex Singleton::_mtx;Singleton::GC Singleton::_gc;void fun(){ for (int i = 0; i < 10; i++){ cout << i << endl; }}void testSing(){ cout << Singleton::getIntance() << endl;}int main(){ Singleton* ps = Singleton::getIntance(); Singleton* ps2 = Singleton::getIntance(); int i = 0; i++; fun(); fun(); thread t1(fun); thread t2(fun); testSing(); testSing(); /*thread t1(testSing); thread t2(testSing);*/ t1.join(); t2.join(); system("pause"); return 0;}1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论