单例模式的实现

 单例模式的概念:

单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。

关键点:

1)一个类只有一个实例       这是最基本的

2)它必须自行创建这个实例

3)它必须自行向整个系统提供这个实例

#include<iostream>
using namespace std;
class CSingleton{
        private:
                static CSingleton *m_pInstance;
                CSingleton(){
                }
                ~CSingleton(){
                        if (m_pInstance == NULL) {
                                return;
                        }
                        delete m_pInstance;
                        m_pInstance = NULL;
                }
        public:
                static CSingleton * GetInstance() {
                        if(m_pInstance == NULL)
                                m_pInstance = new CSingleton();
                        return m_pInstance;
                }
};
CSingleton* CSingleton::m_pInstance = NULL;//类的静态成员变量需要在类外边初始化

int main() {
    CSingleton* single1 = CSingleton::GetInstance();
    CSingleton* single2 = CSingleton::GetInstance();
    if (single1 == single2) {
        cout<<"Same"<<endl;
    }
    return 0;
}

 

posted @ 2017-04-11 20:37  倾耳听  阅读(99)  评论(0编辑  收藏  举报