2013-02-09 20 views
1

在典型的單例中,當第一次調用getInstance()時會調用構造函數。我需要的是分離init和getInstance函數。 init函數必須使用構造函數創建實例,並且getInstance只能在調用init函數時使用(否則會引發異常)。我怎樣才能做到這一點?從get_instance()中分離出來的單例構造函數

Singleton::init(required argument); //calls constructor 
    Singleton::getInstance(); //only possible if init had been called, otherwise throws exception 
+1

不要使用單和問題就解決了。 – 2013-02-09 22:33:52

+0

你的問題是什麼? – 2013-02-09 22:33:58

+0

嗯。你正在着手解決的根本問題是什麼?單身模式可能不是你的答案。 – Johnsyweb 2013-02-09 22:40:19

回答

2

在init方法中設置一個表示init成功的bool。如果getInstance方法爲false,則拋出異常。

您可以將其作爲靜態私人成員存儲在課堂中。

#include <iostream> 
class Single 
{ 
public: 
    static void init(int x) 
    { 
     single.number = x; 
     inited = true; 
    } 

    static Single & GetInstance() 
    { 
     //Do exception stuff here.... 
     if(inited) 
     { 
      std::cout << "Inited" << std::endl; 
     } 
     else 
     { 
      std::cout << "NOT Inited" << std::endl; 
     } 
     return single; 
    } 


    void printTest() 
    { 
    std::cout << single.number << std::endl; 
    } 

private: 
    Single() : number(5) 
    { 
     std::cout << "Construction " << std::endl; 
    } 

    int number; 
    static bool inited; 
    static Single single; 
}; 

bool Single::inited = false; 
Single Single::single; 

int main() 
{ 
    std::cout << "Entering main" << std::endl; 

    Single::GetInstance(); 
    Single::init(1); 
    Single::GetInstance().printTest(); 

} 

程序輸出:

Construction 
Entering main 
NOT Inited 
Inited 
1 
+0

是的,但我仍然不知道應該在哪裏存儲它的靜態實例。我需要調用構造函數,這是我的問題。如果初始化函數是普通成員函數,那會起作用。 – user1873947 2013-02-09 22:30:02

+0

@ user1873947上面顯示的示例 – 2013-02-09 22:34:15

+0

謝謝,但仍然如何將構造函數放到init方法中?我認爲這樣我仍然不能使用init()調用實例構造函數。 – user1873947 2013-02-09 22:36:51

相關問題