C/C++之单例模式实现

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

#include <iostream>
#include <string>
using namespace std;

class Singelton
{
private:
        Singelton(){}
        static Singelton* singel;

public:
        static Singelton* GetInstance()
        {
                if(singel == NULL)
                {
                        singel = new Singelton();
                }
                return singel;
        }

};
Singelton* Singelton::singel = NULL;//注意静态变量类外初始化

//客户端:
int main()
{
        Singelton* s1=Singelton::GetInstance();
        Singelton* s2=Singelton::GetInstance();
        if(s1 == s2)
                cout<<"ok"<<endl;
        else
                cout<<"no"<<endl;        
      return 0;
}
posted @ 2015-08-13 10:44  Parishe  阅读(620)  评论(0编辑  收藏  举报