首页 > 编程 > C++ > 正文

C++实现 单例模式实例详解

2020-01-26 14:10:11
字体:
来源:转载
供稿:网友

设计模式之单例模式C++实现

一、经典实现(非线程安全)

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; } 

二、懒汉模式与饿汉模式

懒汉:故名思义,不到万不得已就不会去实例化类,也就是说在第一次用到类实例的时候才会去实例化,所以上边的经典方法被归为懒汉实现;

饿汉:饿了肯定要饥不择食。所以在单例类定义的时候就进行实例化。

特点与选择

由于要进行线程同步,所以在访问量比较大,或者可能访问的线程比较多时,采用饿汉实现,可以实现更好的性能。这是以空间换时间。在访问量较小时,采用懒汉实现。这是以时间换空间。

线程安全的懒汉模式

1.加锁实现线程安全的懒汉模式

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.内部静态变量实现懒汉模式

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; } 

饿汉模式(本身就线程安全)

class Singleton {   public:     static Singleton* getInstance();   protected:     Singleton(){}   private:     static Singleton* p; };  Singleton* Singleton::p = new Singleton; Singleton* Singleton::getInstance() {   return p; } 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表