设计模式——singleton

之前对单例比较熟悉,现在了解到可继承的单例类,记录下来,以防忘记。

1.一直以来忽略单例的析构的问题,平时用惯了第二种写单例的方法,但是没有想过这样用的好处

方法一:

class CSingleton

{

public:

static CSingleton* GetInstance();

private:

    CSingleton(){};

    static CSingleton * m_pInstance;

class CGarbo //它的唯一工作就是在析构函数中删除CSingleton的实例

{

        public:

            ~CGarbo()

            {

                if( CSingleton::m_pInstance )

                  delete CSingleton::m_pInstance;

}

         }

        Static CGabor Garbo; //定义一个静态成员,程序结束时,系统会自动调用它的析构函数

};

方法二:

class CSingleton

{

    //其他成员

    public:

        static Singleton *GetInstance()   //使用局部变量的方法

{

    static Singleton *instance = new  singleton();

    return instance;

}

        private:

            Singleton() {};

};

 

(2)多线程的单例类:

class Singleton

{

public:

static Singleton& GetInstance();

private:

Singleton();

~Singleton();

/*   Use auto_ptr to make sure that the allocated memory for instance

**  will be released when program exits (after main() ends).

*/

static std::auto_ptr<Singleton> s_instance;   

friend class std::auto_ptr<Singleton>;

Singleton(const Singleton&);

Singleton& operator =(const Singleton&);

};

 

(3) 可继承的单例类:

template <typename T>

class ISingleton

{

public:

static T& GetInstance() {

static boost::mutex s_mutex; if (s_instance.get() == NULL) {

boost::mutex::scoped_lock lock(s_mutex);

if (s_instance.get() == NULL) {

s_instance.reset(new T());

} // 'lock' will be destructed now. 's_mutex' will be unlocked.

}

return *s_instance;

 }

protected:

ISingleton() { }

 ~ISingleton() { }

// Use auto_ptr to make sure that the allocated memory for instance

// will be released when program exits (after main() ends).

static std::auto_ptr<T> s_instance;

private: ISingleton(const Singleton&);

ISingleton& operator =(const ISingleton&);

};

template <typename T>

std::auto_ptr<T> ISingleton<T>::s_instance;

 

 

//子类

class MySingleton : public ISingleton<MySingleton>

{

public: // blah blah

private:

MySingleton() {

cout << "Construct MySingleton" << endl;

}

~MySingleton() { c

out << "Destruct MySingleton" << endl;

 }

 friend ISingleton<MySingleton>;

 friend class auto_ptr<MySingleton>;

MySingleton(const MySingleton&);

MySingleton& operator =(const MySingleton&);

};

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值