c++设计模式(八)

设计模式分为三大类:
创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式原型模式
结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。
行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

单例模式又分为懒汉式和饿汉式

#include<iostream>
#include<pthread.h>

using namespace std;

class Singleton
{
private:
	static Singleton *mInstance;
	static int handlecount;
	
private:
	Singleton()
	{
		
	}
	
public:
	static Singleton *GetInstance()
	{
		if(NULL == mInstance)
		{
			usleep(100000);
			mInstance = new Singleton;
		}
		handlecount++;
		return mInstance;
	}
	static int Gethandcount()
	{
		return handlecount;
	}
	
	int dele()
	{
		handlecount--;
		if(handlecount==0 && mInstance != NULL)
		{
			delete mInstance;
			mInstance = NULL;
		}
		return handlecount;
	}
};

Singleton *Singleton::mInstance = NULL;
int Singleton::handlecount = 0;


void * create1(void *arg)
{
	Singleton * s1=Singleton::GetInstance();
	cout<<s1<<endl;
}


int main()
{
	int ret;
	pthread_t id[20];
	
	for(int i=0;i < 20;i++)
	{
		ret = pthread_create(&id[i],NULL,create1,NULL);
		if(ret != 0)
		{
			perror("pthread_create");
		}
	}
	
	void *value;
	for(int i = 0;i < 20;i++)
	{
		
		pthread_join(id[i],&value);
	}
	
	return 0;
}


答案是20个不一样的地址。


而饿汉式

#include<iostream>
#include<pthread.h>

using namespace std;

class Singleton
{
private:
	static Singleton *mInstance;
	static int handlecount;
	
private:
	Singleton()
	{
		
	}
	
public:
	static Singleton *GetInstance()
	{
		
		handlecount++;
		return mInstance;
	}
	static int Gethandcount()
	{
		return handlecount;
	}
	
	int dele()
	{
		handlecount--;
		if(handlecount==0 && mInstance != NULL)
		{
			delete mInstance;
			mInstance = NULL;
		}
		return handlecount;
	}
};

Singleton *Singleton::mInstance = new Singleton;
int Singleton::handlecount = 0;


void * create1(void *arg)
{
	Singleton * s1=Singleton::GetInstance();
	cout<<s1<<endl;
}


int main()
{
	int ret;
	pthread_t id[20];
	
	for(int i=0;i < 20;i++)
	{
		ret = pthread_create(&id[i],NULL,create1,NULL);
		if(ret != 0)
		{
			perror("pthread_create");
		}
	}
	
	void *value;
	for(int i = 0;i < 20;i++)
	{
		
		pthread_join(id[i],&value);
	}
	
	return 0;
}


答案是20个相同的地址。

单例模式的作用是保证为一个类只生成唯一的实例对象。也就是说,在整个程序空间中,该类只存在一个实例对象。

懒汉式和饿汉式的区别就在于懒汉式是在程序运行到那时才会分配空间,而饿汉式则是已经提前分配好空间

猜你喜欢

转载自blog.csdn.net/chenlj_1/article/details/80378041