单件模式(Singleton)

意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

常用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;

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值