单例模式C++实现

1. 饿汉模式

class Singleton
{
    private:
    static  Singleton  instance;
    Singleton(){std::cout<<"construct "<<std::endl;}
    Singleton(const Singleton&);
    public:
     ~Singleton(){std::cout<<"destroy"<<std::endl;};
    static Singleton*  GetSingleton()
    {
      return   &instance;
    }
    Singleton Singleton::instance;

2.饿汉模式
a.局部静态变量的创建是线程安全的。

class SingletonB
{
  public:
   static SingletonB* getinstance()
   {
       static SingletonB instance;
       return &instance;
   }
   private:
    SingletonB(){};
    SingletonB(const SingletonB&);
};

b.加锁

class SingletonC
{
   private:
   SingletonC(){cout<<"construct"<<endl;}
   SingletonC(const SingletonC&);
   static SingletonC* instance;
   public:
   static SingletonC* getinstance()
   {
         if(instance==0)
         {
             unique_lock<mutex>guard(m);
             instance=new SingletonC();
         }
         return instance;
   }
};
SingletonC* SingletonC::instance=0;

c.利用pthread_once()函数

class SingletonD
{
   private:
   SingletonD(){cout<<"construct"<<endl;}
   SingletonD(const SingletonC&);
   static SingletonD* instance;
   static pthread_once_t  ponce_;
   static void init()
   {
       instance=new SingletonD();
   }
   public:
   static SingletonD* getinstance()
   {
         pthread_once(&ponce_,&init);
   }
};
pthread_once_t SingletonD::ponce_ = PTHREAD_ONCE_INIT;
SingletonD*SingletonD:: instance=0;

你可能感兴趣的:(C++,c++,设计模式)