c++设计模式——单例模式

单例模式

  1. 一个类只允许创建唯一的对象
  2. 禁止在类的外部创建对象:私有化构造函数:private或protected
  3. 类的内部维护唯一对象:静态成员变量
  4. 提供访问单例对象的方法:静态成员函数,返回在类内部唯一构造的实例

创建方式

  1. 饿汉式:单例对象无论用或不用,程序启动即创建。
  2. 懒汉式:单例对象在用的时候再创建,不用即销毁。

一:

#include <iostream>
using namespace std;
 
class Singleton
{
    public:
        static Singleton *GetInstance()
        {
            if (m_Instance == NULL )
            {
                m_Instance = new Singleton ();
            }
            return m_Instance;
        }
     
        static void DestoryInstance()
        {
            if (m_Instance != NULL )
            {
                delete m_Instance;
                m_Instance = NULL ;
            }
        }
        // This is just a operation example
        int GetTest()
        {
            return m_Test;
        }
     
    private:
        Singleton()
        {
            m_Test = 10;
        }
        static Singleton *m_Instance;
        int m_Test;
};
Singleton *Singleton::m_Instance = NULL;
 
int main()
{
    Singleton *singletonObj=Singleton::GetInstance();
    
    cout<<singletonObj->GetTest()<<endl;
    Singleton::DestoryInstance();
    return 0;
}

二:多线程下单例模式实现

#include <iostream>
using namespace std;
 
class Singleton
{
    public:
        static Singleton *GetInstance()
        {
            if (m_Instance == NULL )
            {
                Lock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
                if (m_Instance == NULL )
                {
                    m_Instance = new Singleton ();
                }
                UnLock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
            }
            return m_Instance;
        }
     
        static void DestoryInstance()
        {
            if (m_Instance != NULL )
            {
                delete m_Instance;
                m_Instance = NULL ;
            }
        }
     
        int GetTest()
        {
            return m_Test;
        }
     
    private:
        Singleton()
        {
            m_Test = 0;
        }
        static Singleton *m_Instance;
        int m_Test;
};
 
Singleton *Singleton ::m_Instance = NULL;
 
int main()
{
    Singleton *singletonObj = Singleton ::GetInstance();
    cout<<singletonObj->GetTest()<<endl;
    Singleton ::DestoryInstance();
 
    return 0;
}

  1.为何要使用双重检查锁定(两次检查null)呢?

  有两个线程同时到达,即同时调用 GetInstance() ,此时由于 m_Instance == null ,所以很明显,两个线程都可以通过第一重的 m_Instance == null ,进入第一重 if 语句后,由于存在锁机制,所以会有一个线程进入 lock 语句并进入第二重 m_Instance == null ,而另外的一个线程则会在 lock 语句的外面等待。而当第一个线程执行完 new  Singleton ()语句后,便会退出锁定区域,此时,第二个线程便可以进入 lock 语句块,此时,如果没有第二重 m_Instance == null 的话,那么第二个线程还是可以调用 new  Singleton ()语句,这样第二个线程也会创建一个 SingleTon实例,这样也还是违背了单例模式的初衷的,所以这里必须要使用双重检查锁定

  2.如果我去掉第一重 m_Instance == null ,程序还是可以在多线程下完好的运行的

  考虑在没有第一重 m_Instance == null 的情况下,当有两个线程同时到达,此时,由于 lock 机制的存在,第一个线程会进入 lock 语句块,并且可以顺利执行 new SingleTon(),当第一个线程退出 lock 语句块时, singleTon 这个静态变量已不为 null 了,所以当第二个线程进入 lock 时,还是会被第二重 m_Instance == null 挡在外面,而无法执行 new Singleton(),所以在没有第一重 m_Instance == null 的情况下,也是可以实现单例模式的?那么为什么需要第一重 singleton == null 呢?这里就涉及一个性能问题了,因为对于单例模式的话,new SingleTon()只需要执行一次就 OK 了,而如果没有第一重 m_Instance == null 的话,每一次有线程进入GetInstance()时,均会执行锁定操作来实现线程同步,这是非常耗费性能的,而如果我加上第一重 m_Instance == null 的话,那么就只有在第一次,也就是 m_Instance ==null 成立时的情况下执行一次锁定以实现线程同步,而以后的话,便只要直接返回 Singleton 实例就 OK 了而根本无需再进入 lock 语句块了,这样就可以解决由线程同步带来的性能问题了。但是,如果进行大数据的操作,加锁操作将成为一个性能的瓶颈;为此,一种新的单例模式的实现也就出现了。

三:

#include <iostream>
using namespace std;
 
class Singleton
{
public:
    static Singleton *GetInstance()
    {
        return const_cast<Singleton *>(m_Instance);//const_cast参考链接:http://www.cnblogs.com/tianzeng/p/9062074.html
    }
 
    static void DestoryInstance()
    {
        if (m_Instance != NULL )
        {
            delete m_Instance;
            m_Instance = NULL ;
        }
    }
 
    int GetTest()
    {
        return m_Test;
    }
 
private:
    Singleton()
    {
        m_Test = 10;
    }
    static const Singleton *m_Instance;//静态变量,在程序初始化之前已经完成 
    int m_Test;
};

const Singleton *Singleton ::m_Instance = new Singleton();
 
int main()
{
    Singleton *singletonObj = Singleton ::GetInstance();
    cout<<singletonObj->GetTest()<<endl;
    Singleton ::DestoryInstance();
    return 0;
}

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

四:

#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()
{
    Singleton *singletonObj=Singleton::GetInstance();
    cout<<singletonObj->GetTest()<<"----->"<<Singleton::GetInstance()<<endl;;
    
    singletonObj = Singleton ::GetInstance();
    cout<<singletonObj->GetTest()<<"----->"<<Singleton::GetInstance()<<endl;
    return 0; 
}

实例销毁

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

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

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

五:

#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 = nullptr ;
                    }
                }
        };
        static GC gc;
};
 
Singleton *Singleton::m_Instance = new Singleton();
Singleton ::GC Singleton::gc;
 
int main()
{
    Singleton *singletonObj = Singleton ::GetInstance();
    cout<<singletonObj->GetTest()<<endl;
 
    return 0;
}

模式扩展

  单例模式和工厂模式在实际项目中经常见到,两种模式的组合。

  一种产品,在一个工厂中进行生产,这是一个工厂模式的描述;而只需要一个工厂,就可以生产一种产品,这是一个单例模式的描述。所以,在实际中,一种产品,我们只需要一个工厂,此时,就需要工厂模式和单例模式的结合设计。由于单例模式提供对外一个全局的访问点,所以,我们就需要使用简单工厂模式中那样的方法,定义一个标识,用来标识要创建的是哪一个单件。

原文地址:https://www.cnblogs.com/tianzeng/p/9062008.html