关于单例模式的一些思考

版本一 Reference:http://tech.ddvip.com/2009-04/1238585011113136.html

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 CGarbo Garbo; // 定义一个静态成员,在程序结束时,系统会调用它的析构函数
 
}


版本二 Reference:http://blog.csdn.net/windboyzsj/article/details/2790485

#include <iostream.h>  
class Singleton 
{ 
public: 
	~Singleton(){cout<<"singleton deconstruct"<<endl;} 
	static Singleton* Instance() 
 	{ 
 		if (_instance == NULL) 
 		{ 
 		   _instance = new Singleton(); 
 		   static Cleaner cl; //延迟到这里  
		} 
 		 return _instance; 
 	} 
 
 	void Print(char* str) 
 	{ 
 	  cout<<"singleton print:"<<str<<endl; 
 	} 
 private: 
 	Singleton(){cout<<"singleton construct"<<endl;} 
 	static Singleton* _instance; 
 	class Cleaner 
 	{ 
 public: 
 	Cleaner(){cout<<"cleaner construct"<<endl;} 
 	~Cleaner() 
 	{ 
 	     cout<<"cleaner deconstruct"<<endl; 
 	     if(Singleton::Instance()) 
	     delete Singleton::Instance(); 
	} 
 }; 
 }; 
 Singleton* Singleton::_instance = NULL; 
 int main(int argc, char* argv[]) 
 { 
 	Singleton::Instance()->Print("print 1"); 
 	Singleton::Instance()->Print("print 2"); 
 	return 0; 
 }

版本三 Reference:http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt

来自IBM的一些研究性文章,此方法也可以借用一下,本人英语比较烂就不献丑了,更详细查看reference,里面写的比较详细

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

        friend class SingletonDestroyer;
        virtual ~Singleton() { }
    private:
        static Singleton* _instance;
        static SingletonDestroyer _destroyer;
    };

    Singleton* Singleton::_instance = 0;
    SingletonDestroyer Singleton::_destroyer;

    Singleton* Singleton::Instance () {
        if (!_instance) {
            _instance = new Singleton;
            _destroyer.SetSingleton(_instance);
        }
        return _instance;
    }


 

class SingletonDestroyer {
    public:
        SingletonDestroyer(Singleton* = 0);
        ~SingletonDestroyer();

        void SetSingleton(Singleton* s);
    private:
        Singleton* _singleton;
    };

    SingletonDestroyer::SingletonDestroyer (Singleton* s) {
        _singleton = s;
    }

    SingletonDestroyer::~SingletonDestroyer () {
        delete _singleton;
    }

    void SingletonDestroyer::SetSingleton (Singleton* s) {
        _singleton = s;
    }


 


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值