C++ implementation of the singleton pattern examples
- 2020-05-19 05:15:22
- OfStack
Design pattern singleton pattern C++ implementation
1. Classic implementation (non-thread safe)
class Singleton
{
public:
static Singleton* getInstance();
protected:
Singleton(){}
private:
static Singleton *p;
};
Singleton* Singleton::p = NULL;
Singleton* Singleton::getInstance()
{
if (NULL == p)
p = new Singleton();
return p;
}
2. Lazy vs. hungry
Lazy guy: it means that you won't instantiate a class unless you have to, that is to say, you will instantiate it the first time you use a class instance.
Hungry man: when you're hungry, you have to be hungry. So instantiate it when the singleton class is defined.
Features and options
Because of the thread synchronization, so in the traffic is relatively large, or may access more threads, the implementation of the hungry han, can achieve better performance. It's space for time. In the traffic is small, using lazy people to achieve. It's time for space.
Thread-safe slacker mode
1. Lock the implementation of thread safety lazy mode
class Singleton
{
public:
static pthread_mutex_t mutex;
static Singleton* getInstance();
protected:
Singleton()
{
pthread_mutex_init(&mutex);
}
private:
static Singleton* p;
};
pthread_mutex_t Singleton::mutex;
Singleton* Singleton::p = NULL;
Singleton* Singleton::getInstance()
{
if (NULL == p)
{
pthread_mutex_lock(&mutex);
if (NULL == p)
p = new Singleton();
pthread_mutex_unlock(&mutex);
}
return p;
}
2. Implement lazy mode with internal static variables
class Singleton
{
public:
static pthread_mutex_t mutex;
static Singleton* getInstance();
protected:
Singleton()
{
pthread_mutex_init(&mutex);
}
};
pthread_mutex_t Singleton::mutex;
Singleton* Singleton::getInstance()
{
pthread_mutex_lock(&mutex);
static singleton obj;
pthread_mutex_unlock(&mutex);
return &obj;
}
Hanky mode (itself thread-safe)
class Singleton
{
public:
static Singleton* getInstance();
protected:
Singleton(){}
private:
static Singleton* p;
};
Singleton* Singleton::p = new Singleton;
Singleton* Singleton::getInstance()
{
return p;
}
Thank you for reading, I hope to help you, thank you for your support of this site!