2012-07-29 21 views
2

可能重複:
Can any one provide me a sample of Singleton in c++?
C++ Singleton design pattern
C++ different singleton implementationsC++單例類的getInstance(如Java)

我需要在C++類的Singleton的一些例子,因爲我從未寫了這樣類。 對於java中的一個例子,我可以聲明一個靜態字段,它是私有的,它在構造函數中初始化,getInstance方法也是靜態的,並返回已經初始化的字段實例。

在此先感謝。

+1

不,首先你需要一個很好的理由來使用單身人士,然後你需要另一個很好的理由,然後*然後*我們可以談論這樣做。 – delnan 2012-07-29 11:01:29

+2

請避免單身。他們幾乎總是工作的錯誤工具。 [閱讀](http://jalf.dk/singleton) – jalf 2012-07-29 11:05:54

+0

搜索之前問:http://stackoverflow.com/questions/1008019/c-singleton-design-pattern – 2012-07-29 11:13:14

回答

1

實施例:
logger.h:

#include <string> 

class Logger{ 
public: 
    static Logger* Instance(); 
    bool openLogFile(std::string logFile); 
    void writeToLogFile(); 
    bool closeLogFile(); 

private: 
    Logger(){}; // Private so that it can not be called 
    Logger(Logger const&){};    // copy constructor is private 
    Logger& operator=(Logger const&){}; // assignment operator is private 
    static Logger* m_pInstance; 
}; 

logger.c:

#include "logger.h" 

// Global static pointer used to ensure a single instance of the class. 
Logger* Logger::m_pInstance = NULL; 

/** This function is called to create an instance of the class. 
    Calling the constructor publicly is not allowed. The constructor 
    is private and is only called by this Instance function. 
*/ 

Logger* Logger::Instance() 
{ 
    if (!m_pInstance) // Only allow one instance of class to be generated. 
     m_pInstance = new Logger; 

    return m_pInstance; 
} 

bool Logger::openLogFile(std::string _logFile) 
{ 
    //Your code.. 
} 

的詳細信息中:

http://www.yolinux.com/TUTORIALS/C++Singleton.html

+1

它的工作原理謝謝:) – 2012-07-29 11:04:38

+0

鏈接到外部資源不是一個好主意。如果這些網站消失了,那麼你的答案對未來的讀者就沒用了。 – 2012-07-29 14:42:17

+0

@LokiAstari - 你說得對。我已經修復它。 – 2012-07-29 14:44:39

4
//.h 
class MyClass 
{ 
public: 
    static MyClass &getInstance(); 

private: 
    MyClass(); 
}; 

//.cpp 
MyClass & getInstance() 
{ 
    static MyClass instance; 
    return instance; 
} 
+1

它工作的感謝,並也@Roee Gavirel給出了相同的答案 – 2012-07-29 11:07:01

+0

尼斯。我總是使用'getInstance'和'== null'。靜態成員的使用很簡單但很智能。 – 2012-07-29 14:49:14

+0

其中一個潛在的問題是,實例會在某個未知的時間點被破壞,可能會導致破壞問題的順序。如果單身人士需要銷燬,我會使用這個解決方案,但如果沒有,這個解決方案會超過90%。 – 2012-07-29 15:50:10