単例モードの餓漢、怠け者

1977 ワード

一、単例モード
単例モードは設計モードの一種であり,本稿では主に単例モードを紹介する.
シングル・スキーマ・コア:クラスにはオブジェクトが1つしか作成できません.システム内のクラスにはインスタンスが1つしかないことを保証し、すべてのプログラム・モジュールで共有されるグローバル・アクセス・ポイントを提供します.
事例:あるサーバでは,そのサーバの構成情報を1つのファイルに格納し,これらのデータは1つの単例オブジェクトによって読み取らなければならず,他のオブジェクトはこの単例オブジェクトによって過去に構成され,このように設計すれば,多くの時間を節約できる.
単例の餓漢モード:
直接コード:
#include
class Singleton
{
  public:
    static Singleton *GetInstance()
    {
      return &m_instance;
    }
  private:
    //      
    Singleton ();
    //        ,   
    Singleton (const Singleton &);
    Singleton& operator=(const Singleton&);
    //   ,   static
    static Singleton m_instance;
};
Singleton Singleton::m_instance;
int main()
{
  return 0;
}

メリット:シンプルなデザイン
欠点:ログインするたびに初期化され、時間がかかり、資源競争が高く、速度が遅い
単例の怠け者モード:
#include
#include
using namespace std;
class Singleton
{
  public:
    static Singleton *GetInstance()
    {
        if(m_Pinstance == nullptr)
        {
          //      (  :   )
          m_mtx.lock();
          if(nullptr == m_Pinstance)
          {
              m_Pinstance = new Singleton;
          }
          m_mtx.unlock();
        }
        return m_Pinstance;
    }
    //   ,       ,  Singleton     ,       ,         。
    class CGarbo{
      public:
            ~CGarbo()
            {
              if(Singleton::m_Pinstance)
              {
                delete Singleton::m_Pinstance;
              }
            }
    };
    //          ,     ,                     
            static CGarbo Garbo;
  private:
            //      ,           
    Singleton ();
    //      
    Singleton operator=(const Singleton&);
    static Singleton *m_Pinstance;
    static mutex m_mtx;
};
Singleton* Singleton::m_Pinstance = nullptr;
Singleton:: CGarbo Garbo;
mutex Singleton::m_mtx;
int main()
{
  return 0;
}

長所:餓漢の欠点です.
ポイント:餓漢は毎回初期化しなければならないが、怠け者は一度初期化することを指す.