单例模式

1.        

特点:

保证一个类仅有一个实例,并提供一个访问它的全局访问点。

单例类可以继承

2.        

实际应用:

如一个工程中,数据库访问对象只有一个,这时,可以考虑使用单例模式。

3.       

code1:

#include <iostream>
using namespace std;
class CSingleton
{
public:
	//创建:
	static CSingleton* GetInstance()
	{
		if(NULL == m_pInstance)
		{
			m_pInstance = new CSingleton();
		}
		return m_pInstance;
	}
	
	//释放空间:
	static void Release()
	{
		if(NULL != m_pInstance)
		{
			delete m_pInstance;
			m_pInstance = NULL;
		}
	}
protected:
	CSingleton()
	{
		cout << "CSingleton" << endl;
	}
	static CSingleton* m_pInstance;
};
//一定要初始化
CSingleton *CSingleton::m_pInstance = NULL;
//单例模式的继承
class CSingleDraw:public CSingleton
{
public:
	static CSingleDraw* GetInstance()
	{
		if(NULL == m_pInstance)
		{
			m_pInstance = new CSingleDraw();
		}
		return (CSingleDraw*)m_pInstance;
	}
protected:
	CSingleDraw()
	{
		cout << "CSingleDraw" << endl;
	}
};
int main(int argc, char**argv)
{
	CSingleDraw* s1 = CSingleDraw::GetInstance();
	CSingleDraw* s2 = CSingleDraw::GetInstance();
	s2->Release();
	system("pause");
	return 0;
}



4.

code2:

#include <iostream>
using namespace std;

class SimpleObject
{
private:
	SimpleObject()
	{
		message = new char[30];
		memset(message,0,30);
	}
public:
	~SimpleObject(){}

	static SimpleObject& GetSimpleOjbct()
	{
		static SimpleObject m_object;
		return m_object;
	}

	void SetSimpleObjectX(int n){x = n;}
	void SetSimpleOjbectY(int n){y = n;}
	void SetSimpleOjbectZ(int n){z = n;}
	void SetSimpleObjectMessage(char* msg){strcpy(message,msg);}
	void ShowObject();
private:
	int x;
	int y;
	int z;
	char* message;
};


void SimpleObject::ShowObject()
{
	cout<<x<<":"<<y<<":"<<z << endl;
	cout<<message<<endl;
}

int main(int agrc,char* argv[])
{
	//创建一个实例A
	SimpleObject A = SimpleObject::GetSimpleOjbct();
	A.SetSimpleObjectX(0);
	A.SetSimpleOjbectY(0);
	A.SetSimpleOjbectZ(0);
	A.SetSimpleObjectMessage("this is SimpleObject A");
	A.ShowObject();
	
	//试图创建另一个实例B
	SimpleObject B = SimpleObject::GetSimpleOjbct();
	B.SetSimpleObjectX(12);
	B.ShowObject();
	
	system("pause");
	return 0;
}

/*
output:
0:0:0
this is SimpleObject A
12:0:0
this is SimpleObject A
*/

4.

iphone的单例

详见http://www.duckrowing.com/2010/05/21/using-the-singleton-pattern-in-objective-c/

你可能感兴趣的:(单例模式)