Singleton模式

一.单件模式的定义

Ensure a class has only one instance, and provides a globel point of access to it.(确保一个类只有一个实例,而且自行实例化并向整个系统提供这个实例)

二.单件模式的结构图释义

这里写图片描述

在singleton模式图中可以看到,我们通过维护一个static的成员变量_instance来记录这个唯一的对象实例。通过提供一个static的接口Instance来获取这个唯一的实例。

三.代码实现

//sinleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__

#include<iostream>
using namespace std;

class singleton
{
    public:
        static singleton* create_instance();//获取唯一的对象实例
    private:
        singleton();
        static singleton *psingleton;//记录唯一的对象实例
};

#endif
//singleton.cpp
#include"singleton.h"

singleton* singleton::psingleton = NULL;//对psingleton进行初始化为NULL
singleton::singleton()
{
    cout<<"This is singleton ctr."<<endl;
}

singleton* singleton::create_instance()
{
    if(singleton::psingleton == NULL)
    {
        singleton::psingleton = new singleton();
    }
    return singleton::psingleton;
}
//main.cpp
#include"singleton.h"

int main(int argc, char const* argv[])
{
    singleton* psgn1 = singleton::create_instance();
    singleton* psgn2 = singleton::create_instance();
    return 0;
}

测试:
这里写图片描述
可见只调用一次构造函数,实例化出一个对象。

四.单例模式的优缺点

五.单例模式中的线程安全问题

六.单例模式的使用场景

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值