设计模式 二

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>

using namespace std;

class Sigleton
{
public:
	static Sigleton *GetInstance()
	{
		if (m_intance == nullptr)
		{
			std::unique_lock <std::mutex> lock(mutex);
			if (m_intance == nullptr)
				m_intance = new Sigleton;
		}
		

		m_count++;

		return m_intance;
	}
	static void Release()
	{
		if (m_count > 0)
			m_count--;
		if (m_intance != nullptr && m_count == 0)
		{
			delete m_intance;

			m_intance = nullptr;
		}
		
	}
private:
	Sigleton()
	{
		std::this_thread::sleep_for(std::chrono::seconds(2));
		cout << "Sigleton 构造函数" << endl;
	}
	static int m_count;
	static Sigleton *m_intance;
	static std::mutex mutex;

};

Sigleton* Sigleton::m_intance = nullptr;
int Sigleton::m_count = 0;
std::mutex Sigleton::mutex;

void func(int i=0)
{
	cout << "第" << i << "个线程开启" << endl;
	Sigleton* ps = Sigleton::GetInstance();
}
int main()
{
	vector<std::thread> v;
	for (int i = 0; i < 10; i++)
	{
		/*std::thread t(func, i+1);
		t.detach();*/

		v.push_back(std::thread(func, i + 1));
	}
	for (int i = 0; i < 10; i++)
		v[i].join();


	system("pause");
	return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Clothes
{
public:
	virtual void show() = 0;
};
class T_shrit:public Clothes
{
public:
	void show()
	{
		cout << "T_shrit" << endl;
	}
};
class Jacket:public Clothes
{
public:
	void show()
	{
		cout << "Jacket" << endl;
	}
};
class Factory
{
public:
	Clothes *CreateClothes(string name)
	{
		if (name == "T恤")
			return new T_shrit;
		if (name == "夹克")
			return new Jacket;
	}
};
int main()
{
	Factory *pf1 = new Factory;
	Clothes*pc1 = pf1->CreateClothes("夹克");

	Clothes *pc2 = pf1->CreateClothes("T恤");

	pc1->show();
	pc2->show();

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值