单例模式

应用:一个类对象频繁创建

懒汉模式:没人要他就不创建,要时再创建,创建时还要加锁,避免创建2个

#include 
#include 
#include 
#include
#include 
#include
#include
using namespace std;
mutex mymutex;
struct node {
public:
	node* get();
private:
	static node *sigton;
};
node* node::sigton = NULL;
node* node::get()
{
	if (sigton == nullptr)
	{
		mymutex.lock();
		sigton = new node();
		mymutex.unlock();
	}
	return sigton;
}
int main()
{
	node t1;
	node *temp = t1.get();
	return 0;
}

饿汉模式:其实就是在全局里面先创建好,因为全局代码优先运行于main里面的,所以也不用加锁。

#include 
#include 
#include 
#include
#include 
#include
#include
using namespace std;
mutex mymutex;
struct node {
public:
	node* get();
private:
	static node *sigton;
};
node* node::sigton = new node();
node* node::get()
{
	return sigton;
}
int main()
{
	node t1;
	node *temp = t1.get();
	return 0;
}

 

你可能感兴趣的:(设计模式)