设计模式(一)单例模式

一、什么是单例模式?

单例模式是类的设计模式,使用这个模式设计出来的类运行期间最多只有一个实例,为什么是最多呢,因为它有可能整个运行完了都没有创建。

既然单例模式这么常见,那么它有什么优点呢?节省内存(仅有一个对象)加快访问速度(不用频繁创建),缺点在于没有接口,不能继承。

二、单例模式适用场景

  • 唯一序列号
  • WEB计数器
  • 创建耗时对象(IO及数据库连接)

要想了解更多,可以看看这个:https://blog.csdn.net/tanyujing/article/details/14160941

三、单例模式的分类

单例模式分为两类:

  • 预加载型
  • 用到再加载型

前者被称为饿汉模式,后者被称为懒汉模式。前者未雨绸缪是一个曾经过过吃不饱穿不暖的日子,所以他总是先创建好,需要时随时都可以拿到,未雨绸缪;后者是一个小康家庭,从来没有过过苦日子,所以他总是用的时候再去创建。个人觉得这两种人呢,都是好人,关键是你对资源的及时性有没有要求。

四、具体实现

无论是衣食无忧型的懒汉还是未雨绸缪型的饿汉,首先要满足的条件就是让用户没法构造,在C++里最简单的方法就是让构造函数私有化。

4.1 未雨绸缪型实现
class Singleton
{
private:
    Singleton(){std::cout<<"Created an singleton"<<endl;}
    static Singleton * pinstance;
public:
    static Singleton * GetInstance(){return pinstance;}
};

Singleton * Singleton::pinstance = new Singleton;//静态成员在main函数之前都创建好了,未雨绸缪啊!!!

其实构造函数可以直接声明为delete,为了观察单例是否是多次调用仅产生一次,所以才使用其等价实现——私有化构造函数。

整个单例类包含:

  • 一个已经delete的构造函数;
  • 一个指new对象的静态指针;
  • 一个返回静态指针的静态方法;

注意:静态成员在主函数执行之前保证已经初始化。上面这种方法是线程安全的。

4.2 衣食无忧型实现

因为该方式是在用户主动调用GetInstance()时才开始创建,所以对象创建放在静态成员函数GetInstance中。

class Singleton
{
public:
	static Singleton * p_instance;
	static Singleton * GetInstance();
private:
	Singleton(){cout<<"Contructor running"<<endl;}
};
Singleton * Singleton::p_instance=nullptr;
Singleton * Singleton::GetInstance()
{
    p_instance=new Singleton();
	return p_instance;
}

要实现多次调用GetInstance()返回相同的对象,上面获得的对象等于调用次数,不符合要求。解决方法很简单,如果指向对象的指针为nullptr那么就不进入new语句,实现如下:

class Singleton
{
public:
	static Singleton * p_instance;
	static Singleton * GetInstance();
private:
	Singleton(){cout<<"Contructor running"<<endl;}
};
Singleton * Singleton::p_instance=NULL;
Singleton * Singleton::GetInstance()
{
    if(p_instance==NULL)
	p_instance=new Singleton();
	return p_instance;
}

在多线程环境下进行测试:

int main()
{
    pthread_t * th;
    vector<pthread_t *> vec_pth;
    for(int i=0;i<100;i++)
    {
        th=new pthread_t;
        vec_pth.push_back(th);
        pthread_create(vec_pth[i],NULL,fun,NULL);
    }
    for(int i=0;i<100;i++)
    {
       pthread_join(*vec_pth[i],NULL);
    }
}

void * fun(void *)
{
    Singleton::GetInstance();
}

不同线程可能同时调用GetInstance(),计算机还没有来得及更新p_instance就已经进入new语句,导致创建了多个对象,运行结果非常不稳定,在我的系统里创建3-5次对象。这是不符合单例的要求的。可以借助线程锁保证每次仅有一个线程进判断,从而保证单例已经顺利创建,其他来的晚的进程就只能返回首个进程创建的对象了。

class Singleton
{
public:
	static Singleton * p_instance;
	static Singleton * GetInstance();
	pthread_mutex_t lo;
private:
    Singleton(){cout<<"Contructor running"<<endl;}
    static pthread_mutex_t lo;
};
Singleton * Singleton::p_instance=nullptr;
Singleton::pthread_mutex_init(&lo);
Singleton * Singleton::GetInstance()
{

	pthread_mutex_lock(&lo);
    if(p_instance==nullptr)
	p_instance=new Singleton();
    pthread_mutex_unlock(&lo);
	
	return p_instance;
}

线程加锁和解锁需要时间,为了解决这个问题,在2004年Scott Meyers and Andrei Alexandrescu在名字为<C++ and the Perils of Double-Checked Locking >中提出double-check机制减少加锁和解锁的次数,最终的代码如下:

class Singleton
{
public:
	static Singleton * p_instance;
	static Singleton * GetInstance();

	Singleton(){cout<<"Contructor running"<<endl;}
private:
};
Singleton * Singleton::p_instance=NULL;
Singleton * Singleton::GetInstance()
{
	if(p_instance==nullptr)
	{
		pthread_mutex_lock(&lo);
	    if(p_instance==nullptr)
    	p_instance=new Singleton();
        pthread_mutex_unlock(&lo);
	}
    pthread_mutex_unlock(&lo);
	
	return p_instance;
}

无论是懒汉还是饿汉都没有考虑拷贝构造、赋值。其实最佳的实现应该是以下方法:

五、C++11标准下实现方法

方法一: 使用返回局部静态变量,这种方法

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <unistd.h>
#include <pthread.h>
using namespace std;

class Singleton
{
public:
    static Singleton & GetInstance2();
private:
	Singleton(){cout<<"Contructor running"<<endl;}
};

Singleton & Singleton::GetInstance2()
{
    static Singleton instance=Singleton();
    return instance;
}   

void * fun(void *)
{
    Singleton::GetInstance2();
}

int main()
{
    pthread_t * th;
    vector<pthread_t *> vec_pth;
    for(int i=0;i<100;i++)
    {
        th=new pthread_t;
        vec_pth.push_back(th);
        pthread_create(vec_pth[i],NULL,fun,NULL);
    }
    for(int i=0;i<100;i++)
    {
       pthread_join(*vec_pth[i],NULL);
    }
}

方法二:callonce

class Singleton {
public:
	static Singleton* getInstance() {
		static std::once_flag onceFlag; // 必须是静态的
		std::call_once(onceFlag, [&] {m_instance = new Singleton(); }); // 只会调用一次
		return m_instance;
	}
	
private:
	Singleton() {} //私有构造函数,不允许使用者自己生成对象,但是必须要实现
	Singleton(const Singleton& other) = delete;
	Singleton& operator = (const Singleton& other) = delete;

private:
	static Singleton* m_instance; //静态成员变量 
};

Singleton* Singleton::m_instance = nullptr; //静态成员需要先初始化

https://en.cppreference.com/w/cpp/thread/call_once


[1]https://zh.wikipedia.org/wiki/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F
[2]https://www.cnblogs.com/restartyang/articles/7770856.html
[3]https://blog.csdn.net/qq_36186690/article/details/82945836
[4]https://stackoverflow.com/questions/2576022/efficient-thread-safe-singleton-in-c

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值