C++ 单态模式实现

  ANSI C++ 中的 Singleton 实现说难不难,说容易也不容易,很多人写 ANSI C++ 的 Singleton class 都有错误。这篇文章讨论怎样在 ANSI c++ 中写 Singleton class, 希望对大家有帮助。

  《设计模式》中把 Singleton 写成返回指针:


 

class Singleton{
public:
    static Singleton* Instance();
protected:
    Singleton();
private:
    static Singleton* _instance;
};

      相应的实现 cpp 文件是:

 

Singleton* Singleton::_instance;
Singleton* Singleton::Instance(){
    if( _instance == 0){
        _instance = new Singleton;
    };
    return _instance;
}

 

    将构造函数设计成 protected 的目的是防止在 class 外面 new ,有人可能会设计成 private ,如果考虑到有可能会继承这个类的话,还是将构造函数设计成 protected 比较好,还需要加一个 virtual 析构函数。为了防止别人复制 Singleton 对象:

 

Singleton* pSingleton = Singleton::Instance();
Singleton s1 = *pSingleton;
Singleton s2 = *pSingleton;
需要将拷贝构造(copy constructor)函数变成 private。


    但是这里存在的问题是,什么时候删除 Singleton 对象?按照 C++ 的一个基本原则,对象在哪里创建就在哪里销毁,这里还应该放一个 destroy 方法来删除 Singleton 对象。如果忘了删除就比较麻烦。Instance 函数还存在多线程同时访问的加锁问题。如果把 Instance 函数开始和结尾放上加锁和解锁,整个函数性能会下降很多。这不是一个好的设计。
    有一个小小的改动,可以避免忘了删除 Singleton 对象带来内存泄露的问题。那就是用 std:auto_ptr 来包含 Singleton 对象,定义一个class static member auto_ptr 对象,在析构的静态 auto_ptr 变量的时候时候自动删除 Singleton 对象。为了不让用户 delete Singleton 对象,需要将析构函数由 public 变成 protected。以下是头文件 SingletonAutoPtr.h :

 

#include <memory>
using namespace std;
class CSingletonAutoPtr
{
private:
    static auto_ptr<CSingletonAutoPtr> m_auto_ptr;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值