Difference between revisions of "CPP/Classes/Singleton"

From ProgrammingExamples
< CPP
Jump to: navigation, search
(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.cpp==
+
==Singleton.h==
 
<source lang="cpp">
 
<source lang="cpp">
#include <iostream>
 
 
 
class Log
 
class Log
 
{
 
{
 
   public:
 
   public:
     static Log* Instance()
+
     static Log& Instance(); //provide static member function to access the unique instance.
    {
+
      if (!instance)  // Only allow one instance of class to be generated.
+
        {
+
        instance = new Log;
+
        }
+
 
+
      return 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
 
      
 
      
    static Log* instance; //store the single instance
+
};
 +
</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>
  
Log* Log::instance = NULL;
+
==Main.cpp==
 +
<source lang="cpp">
 +
#include <iostream>
 +
#include "Singleton.h"
  
 
int main(int argc, char* argv[])
 
int main(int argc, char* argv[])
 
{
 
{
   Log::Instance()->val = 2.0;
+
   Log::Instance().val = 2.0;
 
    
 
    
   std::cout << "val = " << Log::Instance()->val << std::endl;;
+
   std::cout << "val = " << Log::Instance().val << std::endl;;
  
return 0;
+
  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;
};