单例模式2.docx
《单例模式2.docx》由会员分享,可在线阅读,更多相关《单例模式2.docx(6页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、=1=1. 最优实现class CSingletonpublic:static CSingleton& GetInstance()static CSingleton theSingleton;return theSingleton;/* more (non-static) functions here */private:CSingleton() / 必须定义, 且为private.CSingleton(const CSingleton&); / 不实现.CSingleton& operator=(const CSingleton&); / 不实现.CSingleton() / 可声明为pub
2、lic, 但这里声明为private没有错, 可被调用.;2. 其它实现class CSingleton:public:static CSingleton* GetInstance()if (!m_pInstance)m_pInstance = new CSingleton;return m_pInstance;/* more (non-static) functions here */private:CSingleton() / 必须定义, 且为private.static CSingleton* m_pInstance;class CGarbo / 它的唯一工作就是在析构函数中删除CSin
3、gleton的实例.public:CGarbo()if (CSingleton:m_pInstance)delete CSingleton:m_pInstance;static CGarbo m_garbo; / 定义一个静态成员, 在程序结束时, 系统会调用它的析构函数.;CSingleton* CSingleton:m_pInstance = NULL; / 这句必须有.=2=C+中的单例模式单例模式很有用,使用单例模式,保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享。但是在程序的开发过程中我们总是遇到一些问题,而这些问题主要集中在单例类的消毁过程中,普通使
4、用的单例模式的类如下:class Singleton:/ 其它成员public:static Singleton * GetInstance()if (m_pInstance = NULL)m_pInstance = new Singleton();return m_pInstance;private:Singleton();static Singleton * m_pInstance;可是这个类在什么时候调用它的析构函数呢,我们怎么消毁它。提供一个公用的destroy函数来进行它的消毁吗,这很不美观。最后我就在网上找到了如果下的代码处理了这个问题:class Singleton:/ 其它成员
5、public:static Singleton * GetInstance().private:Singleton();static Singleton * m_pInstance;class CGarbo / 它的唯一工作就是在析构函数中删除Singleton的实例public:CGarbo()if (Singleton:m_pInstance)delete Singleton:m_pInstance;static CGarbo Garbo; / 定义一个静态成员,在程序结束时,系统会调用它的析构函数这是非常好的方法,静态成员对象 Garbo 在析构时会自动的消毁单例,我们不用再担心这个问题
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 模式
限制150内