单例模式(C++)

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

class singleton
{
private:
    singleton(){}; //构造函数为private,禁止客户new出实例
    virtual ~singleton()
    {
        if (instance!=NULL)
            delete instance;
    };

    static singleton *instance;

public:
    static singleton *GetInstance()
    {
        if (instance==NULL)
        {
            instance = new singleton;
        }
        return instance;
    }
};
singleton *singleton::instance=NULL;

int main()
{
    singleton *s1=singleton::GetInstance();
    singleton *s2=singleton::GetInstance();

    if (s1==s2)
    {
        cout<<"同一个实例"<<endl;
    }
    
    system("pause");
    return 0;
}

 

posted @ 2014-02-10 16:01  Dsp Tian  阅读(720)  评论(0编辑  收藏  举报