單例模式(C++)

Dsp Tian發表於2014-02-10
#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;
}

 

相關文章