单列模式

1.单列模式的定义

保证一个类只有一个实例存在,同时提供能对该实例加以访问的静态方法。

2.为什么要使用单列模式

在整个程序空间使用全局变量,共享资源;

大规模系统中,为了性能的考虑,需要节省对象的创建时间等。

3.实现单列模式的步骤

a)  构造函数私有化

b)  提供一个公有的静态方法

c)  在类中定义一个指向本类静态变量指针

4.单列模式的分类

a)懒汉式

懒得给你new对象,等你需要的时候再new;

缺点:当懒汉式遇上多线程时,需要考虑线程同步问题,因为可能出现多个线程同时创建对象的问题,这样就导致单列模式名存实亡,因为单列模式需要保证一个类只有一个实列存在。

优点:节省内存空间,需要时才分配。

b)饿汉式

管你需不需要,我先把对象给你new出来再说。

缺点:浪费空间。

优点:当饿汉式遇上多线程,不需要考虑线程同步问题,因为对象已经事先new出来了。

5.代码实现

5.1懒汉式

#include <iostream>
using namespace std;
//懒汉式
class Singelton
{
private:
    Singelton()
    {
        cout << "Singelton 构造函数执行" << endl;
    }
    static Singelton *m_psl;
public:
    static Singelton *getInstance()
    {
        if (m_psl == NULL)
        {
            m_psl = new Singelton;
        }
        return m_psl;
    }

    static void FreeInstance()
    {
        if (m_psl != NULL)
        {
            delete m_psl;
            m_psl = NULL;
        }
    }
};
Singelton *Singelton::m_psl = NULL;//先初始化为空,等需要的时候再new

void test()
{

    Singelton *p1 = Singelton::getInstance();
    Singelton *p2 = Singelton::getInstance();

    if (p1 == p2)
    {
        cout << "是同一个对象" << endl;
    }
    else
    {
        cout << "不是同一个对象" << endl;
    }
    Singelton::FreeInstance();
    return;
}

void main()
{
    test();
    system("pause");
}

5.2饿汉式

#include <iostream>
using namespace std;
//饿汉式
class Singelton
{
private:
    Singelton()
    {
        cout << "Singelton 构造函数执行" << endl;
    } 

  static Singelton *m_psl;
public:
    static Singelton *getInstance()
    {
        return m_psl;
    }

    static void FreeInstance()
    {
        if (m_psl != NULL)
        {
            delete m_psl;
            m_psl = NULL; 
        }
    }
};//饿汉式
Singelton *Singelton::m_psl = new Singelton;

void test()
{
    Singelton *p1 = Singelton::getInstance();
    Singelton *p2 = Singelton::getInstance();

    if (p1 == p2)
    {
        cout << "是同一个对象" << endl;
    }
    else
    {
        cout << "不是同一个对象" << endl;
    }
    Singelton::FreeInstance();
    return ;
}

void main()
{
    test();
    system("pause");
}

5.3懒汉式遇上多线程

#include <iostream>
#include<pthread.h>
using namespace std;
//懒汉式+多线程
class Singelton
{
private:
    Singelton()
    {
        cout << "Singelton 构造函数执行" << endl;
    }
    static Singelton *m_psl;
    static pthread_mutex_t mutex;
public:
    static Singelton *getInstance()
    {
        if (m_psl == NULL)//使用两次判断,避免平凡的加解锁造成不必要的开销
        {
            pthread_mutex_lock(&mutex);
            if (m_psl == NULL)
            {
                m_psl = new Singelton;
            }
            pthread_mutex_unlock(&mutex);
        }
        return m_psl;
    }

    static void FreeInstance()
    {
        if (m_psl != NULL)
        {
            delete m_psl;
            m_psl = NULL;
        }
    }
};
Singelton *Singelton::m_psl = NULL;
pthread_mutex_t Singelton::mutex;
原文地址:https://www.cnblogs.com/LifeoFHanLiu/p/9948309.html