龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

C++设计模式之单例模式(3)

时间:2014-10-01 02:25来源:网络整理 作者:网络 点击:
分享到:
因为静态初始化在程序开始时,也就是进入主函数之前,由主线程以单线程方式完成了初始化,所以静态初始化实例保证了线程安全性。在性能要求比较高

因为静态初始化在程序开始时,也就是进入主函数之前,由主线程以单线程方式完成了初始化,所以静态初始化实例保证了线程安全性。在性能要求比较高时,就可以使用这种方式,从而避免频繁的加锁和解锁造成的资源浪费。由于上述三种实现,都要考虑到实例的销毁,关于实例的销毁,待会在分析。由此,就出现了第四种实现方式:

实现四:

复制代码 代码如下:

/*
** FileName     : SingletonPatternDemo4
** Author       : Jelly Young
** Date         : 2013/11/20
** Description  : More information, please go to http://www.jb51.net
*/
 
#include <iostream>
using namespace std;
 
class Singleton
{
public:
    static Singleton *GetInstance()
    {
        static Singleton m_Instance;
        return &m_Instance;
    }
 
    int GetTest()
    {
        return m_Test++;
    }
 
private:
    Singleton(){ m_Test = 10; };
    int m_Test;
};
 
int main(int argc , char *argv [])
{
    Singleton *singletonObj = Singleton ::GetInstance();
    cout<<singletonObj->GetTest()<<endl;
 
    singletonObj = Singleton ::GetInstance();
    cout<<singletonObj->GetTest()<<endl;
}

以上就是四种主流的单例模式的实现方式,如果大家还有什么好的实现方式,希望大家能推荐给我。谢谢了。

实例销毁

在上述的四种方法中,除了第四种没有使用new操作符实例化对象以外,其余三种都使用了;我们一般的编程观念是,new操作是需要和delete操作进行匹配的;是的,这种观念是正确的。在上述的实现中,是添加了一个DestoryInstance的static函数,这也是最简单,最普通的处理方法了;但是,很多时候,我们是很容易忘记调用DestoryInstance函数,就像你忘记了调用delete操作一样。由于怕忘记delete操作,所以就有了智能指针;那么,在单例模型中,没有“智能单例”,该怎么办?怎么办?

那我先从实际的项目中说起吧,在实际项目中,特别是客户端开发,其实是不在乎这个实例的销毁的。因为,全局就这么一个变量,全局都要用,它的生命周期伴随着软件的生命周期,软件结束了,它也就自然而然的结束了,因为一个程序关闭之后,它会释放它占用的内存资源的,所以,也就没有所谓的内存泄漏了。但是,有以下情况,是必须需要进行实例销毁的:

1.在类中,有一些文件锁了,文件句柄,数据库连接等等,这些随着程序的关闭而不会立即关闭的资源,必须要在程序关闭前,进行手动释放;

3.具有强迫症的程序员。

以上,就是我总结的两点。

虽然,在代码实现部分的第四种方法能满足第二个条件,但是无法满足第一个条件。好了,接下来,就介绍一种方法,这种方法也是我从网上学习而来的,代码实现如下:

复制代码 代码如下:

/*
** FileName     : SingletonPatternDemo5
** Author       : Jelly Young
** Date         : 2013/11/20
** Description  : More information, please go to http://www.jb51.net
*/
 
#include <iostream>
using namespace std;
 
class Singleton
{
public:
    static Singleton *GetInstance()
    {
        return m_Instance;
    }
 
    int GetTest()
    {
        return m_Test;
    }
 
private:
    Singleton(){ m_Test = 10; }
    static Singleton *m_Instance;
    int m_Test;
 
    // This is important
    class GC
    {
    public :
        ~GC()
        {
            // We can destory all the resouce here, eg:db connector, file handle and so on
            if (m_Instance != NULL )
            {
                cout<< "Here is the test" <<endl;
                delete m_Instance;
                m_Instance = NULL ;
            }
        }
    };
    static GC gc;
};
 
Singleton *Singleton ::m_Instance = new Singleton();
Singleton ::GC Singleton ::gc;
 
int main(int argc , char *argv [])
{
    Singleton *singletonObj = Singleton ::GetInstance();
    cout<<singletonObj->GetTest()<<endl;
 
    return 0;
}

精彩图集

赞助商链接