C++ Singleton design pattern

The singleton pattern is simplest design pattern, it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance. Also provides a global point of access to that instance. There two important use of singleton design pattern :
  • One instance of a class is created.
  • It provides a global point of access to the object.
Let see one simple example of singleton pattern :

#include <string>

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

private:
   Logger(){};  // Private default constructor
   Logger(Logger const&){};             // copy constructor is private
   Logger& operator=(Logger const&){};  // assignment operator is private
   static Logger* m_pInstance;  //Static member 
};

// Global static pointer
Logger* Logger::m_pInstance = NULL;  

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

   return m_pInstance;
}

bool Logger::openLogFile(std::string _logFile)
{
   ...
}
Explanation :

  • instance() function returns a pointer to a static variable and thus is declared static.
  • Only instance() can call the constructor. Public access to the constructor is denied.
  • The constructor, copy constructor and assignment operator are declared as private.
  • The life of the singleton is for the duration of the application.
Usage:
Logger::Instance()->openLogFile("logFile.txt");

Examples and usages :
  1. Logger Classes - Logger class is implemented using singleton pattern and all application is using same instance of class.
  2. Configuration Classes - In application configuration class also using singleton design pattern. only one time configuration setting is loaded by application.
  3.  Accessing resources in shared mode - A singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

1 comment:

  1. Borgata Hotel Casino & Spa | Oyster Hotel Reviews
    Borgata Hotel Casino & 승부사 온라인 환전 Spa 이빨빠지는꿈 reviews and the Borgata Hotel 바카라 사이트 주소 Casino & Spa room rates, Waterfront Conference 사설토토 Center. The hotel's 벳 인포 승무패 계산기 room rate was 8.3 and

    ReplyDelete