I had used singleton design pattern in one of my projects. And in this post I will express my views about it.
Singleton design pattern is a creational design pattern. This design pattern ensures that only one object is created in the lifetime of the program.
The object is created at the time of first access and the same instance is used thereafter in the entire program. This can be achieved by making constructor, destructor, copy constructor and assignment operator all private in the class.
Check out the basic example of a singleton class below:
class SingletonExample
{
public:
static SingletonExample *GetInstance()
{
return (obj ? obj : new SingletonExample());
}
void FreeSingleton()
{
free(obj);
obj = NULL;
}
private:
static SingletonExample *obj;
SingletonExample();
~SingletonExample();
SingletonExample (const SingletonExample&);
SingletonExample& operator=(const SingletonExample&);
};
The above singleton class solves most of the issues but what if there are two threads and both threads are called at same time and both try to create the instance?
To prevent creation of another instance, you need to use mutex in this case. By locking and unlocking the mutex in the critical section of GetInstance function, you can fix the issue:
In a project, if you need to create a Logger class which logs the user data to a file, Singleton is the best design pattern to use.
Please let us know in comments if you have any queries about the Singleton Design Pattern.
Related Posts