Difference between revisions of "CPP/Classes/Singleton"
From ProgrammingExamples
< CPP
Daviddoria (Talk | contribs) (Created page with '==Singleton.cpp== <source lang="cpp"> #include <iostream> class Log { public: static Log* Instance() { if (!instance) // Only allow one instance of class to be…') |
(→Singleton.cpp) |
||
Line 1: | Line 1: | ||
− | ==Singleton. | + | ==Singleton.h== |
<source lang="cpp"> | <source lang="cpp"> | ||
− | |||
− | |||
class Log | class Log | ||
{ | { | ||
public: | public: | ||
− | static Log | + | static Log& Instance(); //provide static member function to access the unique instance. |
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
double val; | double val; | ||
private: | private: | ||
− | Log(){} | + | Log(){}; //prevent construction from outside this class' methods |
Log& operator=(const Log&); //prevent assignment | Log& operator=(const Log&); //prevent assignment | ||
− | Log(const Log&);//prevent copy construction | + | Log(const Log&); //prevent copy construction |
− | + | }; | |
+ | </source> | ||
+ | ==Singleton.cpp== | ||
+ | <source lang="cpp"> | ||
+ | Log& Log::Instance() { | ||
+ | static Log instance; //create as a static object, i.e. will only be created once. | ||
+ | return instance; | ||
}; | }; | ||
+ | </source> | ||
− | + | ==Main.cpp== | |
+ | <source lang="cpp"> | ||
+ | #include <iostream> | ||
+ | #include "Singleton.h" | ||
int main(int argc, char* argv[]) | int main(int argc, char* argv[]) | ||
{ | { | ||
− | Log::Instance() | + | Log::Instance().val = 2.0; |
− | std::cout << "val = " << Log::Instance() | + | std::cout << "val = " << Log::Instance().val << std::endl;; |
− | + | return 0; | |
− | } | + | }; |
</source> | </source> |
Latest revision as of 22:53, 30 November 2010
Singleton.h
class Log { public: static Log& Instance(); //provide static member function to access the unique instance. double val; private: Log(){}; //prevent construction from outside this class' methods Log& operator=(const Log&); //prevent assignment Log(const Log&); //prevent copy construction };
Singleton.cpp
Log& Log::Instance() { static Log instance; //create as a static object, i.e. will only be created once. return instance; };
Main.cpp
#include <iostream> #include "Singleton.h" int main(int argc, char* argv[]) { Log::Instance().val = 2.0; std::cout << "val = " << Log::Instance().val << std::endl;; return 0; };