Wednesday, November 3, 2010

C++ Series - design patterns - 1

Singleton design pattern - Most commonly used pattern and most powerful pattern if used properly.

To say about this design pattern in a single sentence ...
This patterns help to create and use a single object instance through your entire program no matter how many time your initiate your class object.

As simple implementation of this is as below:


class DBconnector{

public:
   static DBconnector* Instance();   -- This function is used to create the object and return the pointer of the object to be used. If the object already exists it just returns the pointer.
   bool openDBconnection(std::string logFile);
   bool inserttoDB();
   bool extractfromDB();

private:

   DBconnector(){};  // The default ctor is made private so that an object cannot be created by just instantiating the class.
   DBconnector(DBconnector const&){};             // copy constructor is made private so that  fails in creating an intermediate object while copying and help to prevent only single instance is prevailing at all moment of time.
   DBconnector& operator=(DBconnector const&){};  // assignment operator so it fails while assigning any other object to this instance.
   static DBconnector* m_pInstance; // Pointer to the actual object , which is single through the program.

};

Multi threading issues with the above program:

Coming soon .. Keep watching.

No comments:

Post a Comment