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

1、单例模式

转载自:https://blog.csdn.net/hj605635529/article/details/70172842

单例模式的适用场景

(1)系统只需要一个实例对象,或者考虑到资源消耗的太大而只允许创建一个对象。

(2)客户调用类的单个实例只允许使用一个公共访问点,除了该访问点之外不允许通过其它方式访问该实例 (就是共有的静态方法)。

单例模式的扩展

允许可变数目的实例,使用与单例控制相似的方法来获得指定个数的对象实例。(即单例类内有多个静态对象指针成员,每次当单例类被引用时随机分配一个实例对象);

(1)饿汉

                特点:线程安全  单例类定义时完成实例化  以空间换时间 适合访问量大 线程多

                设计思路: 构造函数私有化;

                                  提供一个私有静态成员指针,指向唯一对象;

                                  提供一个公有静态成员函数,返回静态成员指针;

                                  把复制构造函数和=操作符也设为私有,防止被复制

                                  private:

                                              singleton(singleton&){}

                                               singleton& operate= (const singleton&){}

#include <iostream>
using namespace std;
class singleton
{
private:

    singleton(){}

    static singleton * p;

public:
    static singleton * Getsingleton()
    {
        return p;
    }
};
singleton * singleton::p = new singleton;

int main()
{
    singleton * m1 = singleton::Getsingleton();
    singleton * m2 = singleton::Getsingleton();
    if(m1 == m2)
        cout<<"饿汉"<<endl;
    system("pause");
    return 0;
}

(2)懒汉

思想:所谓懒汉模式,就是尽可能晚的创建这个对象的实例,即在单例类第一次被引用时将自己初始化;其实C++里很多地方都是类似这样的思想,比如晚绑定,写时拷贝技术等,就是尽量使资源的利用最大化,不要让空闲的人还占着有限的资源。

          特点:非线程安全,第一次使用对象时才完成实例化,以时间换空间,用于访问量小,线程少。

          设计思路: 为了线程安全 线程同步 采用双重加锁

#include<iostream>
#include<pthread.h>
using namespace std;
class singleton
{
    protected:
        singleton()
        {   
            pthread_mutex_init(&mutex,NULL);
        }   
    private:
        static singleton * p;
    public:
        static pthread_mutex_t mutex;
        static singleton * Getsingleton()
        {   
            if(p == NULL)
            {   
                pthread_mutex_lock(&mutex);
                if(p == NULL)
                    p = new singleton();
                pthread_mutex_unlock(&mutex);
            }   
            return p;
        }   
};
pthread_mutex_t singleton::mutex;
singleton * singleton::p = NULL;
int main(){                                                                                                                                                                                                            
    singleton* m1 = singleton::Getsingleton();
    singleton* m2 = singleton::Getsingleton();
    if(m1 == m2) 
        cout<<"lazy";
    return 0;
}








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值