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個相同的地址。

單例模式的作用是保證爲一個類只生成唯一的實例對象。也就是說,在整個程序空間中,該類只存在一個實例對象。

懶漢式和餓漢式的區別就在於懶漢式是在程序運行到那時纔會分配空間,而餓漢式則是已經提前分配好空間

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章