【Demllie C++ Design Pattern】Singleton Pattern Learning

需求

用在多线程中,保证实例的唯一性。


代码
#include <iostream>
#include<thread>
using namespace std;

class Singleton {
public:
	//单例模式不允许拷贝构造函数
	Singleton(Singleton& ) = delete;

	//不允许重载等号
	void operator=(const Singleton& ) = delete;


	static Singleton* getInstance(const string& _s) {
		if (self == nullptr)self = new Singleton(_s);
		return self;
	}

	string getString()const { return s; }
	


	void setup() const{
		cout << "setup => " << s << endl;
	}
	void draw() const{
		cout << "draw => " << s << endl;
	}



protected:
	string s;
	static Singleton* self;//单例模式的实例指针

	//实际生成实例的构造函数
	Singleton(const string _s) { s = _s; }

};

//初始化实例指针
Singleton* Singleton::self = nullptr;



void _fun(string _s) {


	this_thread::sleep_for(std::chrono::milliseconds(1000));//等待一秒
	Singleton* s = Singleton::getInstance(_s);
	cout << s->getString() << endl;
	s->setup();
	s->draw();

}


void fun1() {
	_fun("fun1");
}
void fun2() {
	_fun("fun2");
}

int main(void) {


	//开两个线程
	thread t1(fun1);
	thread t2(fun2);
	t1.join();
	t2.join();

	return 0;
}
结果
fun2
fun2
setup => fun2
draw => fun2
setup => fun2
draw => fun2

fun2fun1

setup => fun1setup => fun2
draw => fun2

draw => fun1
fun1fun1
setup =>
setup => fun1fun1
draw =>
fun1draw =>
fun1
fun1
setup => fun1
draw => fun1
fun1
setup => fun1
draw => fun1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

念心科道尊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值