1. 程式人生 > >設計一個類只能生成該類的一個例項

設計一個類只能生成該類的一個例項

class Singleton
{
public:

    Singleton()
    {
        if (_count == 0)
        {
            cout << "進行建構函式" << endl;
            _count++;
        }
        else
        {
            cout << "構造失敗" << endl;
        }
    }
private:
    static int _count;
};
int Singleton::_count=0
; void test() { Singleton t1; Singleton t2; } int main() { test(); system("pause"); return 0; }
//只適用於單執行緒,多執行緒需要加鎖
class Singleton
{
public:
    static Singleton* GetConstuct()
    {
        if (instance == NULL)
        {
            instance = new Singleton();
            return
instance; } return NULL; } private: static Singleton* instance; Singleton() { cout << "進行建構函式" << endl; } }; Singleton* Singleton::instance = NULL; void test() { Singleton* t1 = Singleton::GetConstuct(); Singleton* t2= Singleton::GetConstuct(); } int
main() { test(); system("pause"); return 0; }
利用靜態建構函式,初始化靜態變數的時候建立例項
class Singleton
{
public:
    static Singleton* GetConstuct()
    {
        return instance;
    }
private:

    Singleton()
    {
        cout << "進行建構函式" << endl;
    }
    static Singleton* instance;

};
Singleton* Singleton::instance = new Singleton();

void test()
{
    Singleton* t1 = Singleton::GetConstuct();
    Singleton* t2 = Singleton::GetConstuct();
}
int main()
{
    test();
    system("pause");
    return 0;
}