您的位置:首页 > 其它

单件模式(Singleton)

2011-12-06 00:32 405 查看
意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

常用c++实现方法:智能指针、静态成员变量、内嵌类、外部显式销毁!

1、智能指针

class CSingleton_1

{

public:

 static CSingleton_1 * Instance()

 {

   if (!s_hInstance.get())

       s_hInstance = std::auto_ptr<CSingleton_1>(new CSingleton_1);

  return s_hInstance.get();

 }

 

protected:

 CSingleton_1();

private:

 static std::auto_ptr<CSingleton_1> s_hInstance;

};

std::auto_ptr<CSingleton_1> CSingleton_1::s_hInstance(NULL);

 

2、静态成员变量

class CSingleton_2

{

public:

 static CSingleton_2 * Instance()

 {

      static CSingleton_2 s;

      return &s;

 }

protected:

 CSingleton_2();

};

 

3、内嵌类

class CSingleton_3

{

public:

 static CSingleton_3 * Instance()

 {

  if (!s_hInstance)

   s_hInstance = new CSingleton_3;

  static CCleaner s_cleaner;

  return s_hInstance;

 }

protected:

 CSingleton_3();

private:

 class CCleaner

 {

 public:

  ~CCleaner()

  {

   if (CSingleton_3::Instance())

        delete CSingleton_3::Instance();

  }

 };

 static CSingleton_3 * s_hInstance;

 //static CCleaner s_cleaner;

};

CSingleton_3* CSingleton_3::s_hInstance = NULL;

//CSingleton_3::CCleaner CSingleton_3::s_cleaner;

 

4、外部显式销毁

class CSingleton_4

{

public:

 static CSingleton_4 * Instance()

  if (!s_hInstance)

   s_hInstance = new CSingleton_4;

  return s_hInstance;

 }

 void Destroy()

 {

  if (s_hInstance)

  {

   delete s_hInstance;

   s_hInstance = NULL;

  }

 }

protected:

 CSingleton_4();

private:

 static CSingleton_4 * s_hInstance;

};

CSingleton_4* CSingleton_4::s_hInstance = NULL;

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class delete null c