设计模式笔记1--单例模式

设计模式笔记1--单例模式

 

1、单例模式介绍

Head First设计模式中解释:用来创建独一无二的,只能有一个实例的对象的入场券。即:该类只能有一个示例,其实现逻辑一般是 构造函数声明为private或protect防止被外部函数实例化,内部保存一个private static的类指针保存唯一的实例,实例的动作由一个public的类方法完成,该方法返回单例类唯一的实例。

单例实现方法被分为两大类:懒汉与饿汉。
懒汉:故名思义,不到万不得已就不会去实例化类,也就是说在第一次用到类实例的时候才会去实例化;
饿汉:饿了肯定要饥不择食。所以在单例类定义的时候就进行实例化。

特点与选择:
由于要进行线程同步,所以在访问量比较大,或者可能访问的线程比较多时,采用饿汉实现,可以实现更好的性能,这是以空间换时间。在访问量较小时,采用懒汉实现。这是以时间换空间。

 

2、代码

1)饿汉模式

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

class Singleton
{
protected:
    Singleton(){}
private:
    static Singleton *instance;
public:
    static Singleton *GetInstance()
    {
        return instance;
    }
};
Singleton* Singleton::instance = new Singleton();
int main()
{
    Singleton *p1 = Singleton::GetInstance();
    Singleton *p2 = Singleton::GetInstance();
    if (p1 == p2)
    {
        cout<<"Two objects is the same instance"<<endl;
    }    
    return 0;
}

2)懒汉模式

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

class Singleton
{
protected:
    Singleton(){}
private:	
    static Singleton *instance;
    static pthread_mutex_t mutex;

public:    
    static Singleton *GetInstance()
    {
        if(NULL == instance){
            pthread_mutex_lock(&mutex);
            if (NULL == instance)
            {
                instance = new Singleton();
            }
            pthread_mutex_unlock(&mutex);
        }
        return instance;
    }
};
Singleton* Singleton::instance = NULL;
pthread_mutex_t Singleton::mutex = NULL;
int main()
{
    Singleton *p1 = Singleton::GetInstance();
    Singleton *p2 = Singleton::GetInstance();
    if (p1 == p2)
    {
        cout<<"Two objects is the same instance"<<endl;
    }    
    return 1;
}

 

3、说明

当前已在mingw32(gcc 4.9.2)上测试通过。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

昕光xg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值