单例模式简介:所谓的单例模式就是你所定义的类,只会产生一个实例对象;

产生单例模式的方式:一种是懒汉式,一种是饿汉式。

懒汉式:就是在你需要使用相应的对象时才去创建。

饿汉式:就是在你程序运行之时便已经创建了相应的对象。

两种方法中都需要将构造函数私有化。

懒汉式的实现参考程序:

#include <iostream>
using namespace std;

class A
{
public :
	static A* get_obj_handle(void);

private :
	A();

private :
	static A * m_a;
};

A* A::m_a = NULL;

A::A()
{
	cout << "using A constructor " << endl;
}

A* A::get_obj_handle(void)
{
	if (NULL == m_a)
	{
		m_a = new A();
	}
	
	return m_a;
}

int main(int argc, char *argv[])
{
	A * a = NULL;
	for (int i = 0; i < 10; ++i)
	{
		a = A::get_obj_handle();
		cout << "This a = " << a << endl;
	}

	return 0;
}

 饿汉式的实现参考程序

     class A    
    {    
    private:    
        A()      
        {    
        }    
    public:    
        static A * GetInstance()    
        {    
            static A instance;     
            return &instance;    
        }    
    };