第62课 单例类模板

本文内容来自于对狄泰学院 唐佐林老师 C++深度解析 课程的学习总结

单例模式

要控制类的对象数目,必须对外隐藏构造函数</font>

思路:
将构造函数的访问属性设置为 private
定义 instance 并初始化为 NULL
当需要使用对象时,访问 instance 的值

  • 空值:创建对象,并且 instance 标记
  • 非空值:返回 instance 标记的对象

实验代码
实现一个单例模式类

#include <iostream>
#include <string>

using namespace std;

class SigleClass
{
private:
    static SigleClass *c_instance;

    SigleClass(const SigleClass&);
    SigleClass& operator = (const SigleClass&);
    SigleClass()
    {
        
    }

public:
    static SigleClass *GetInstance();

    void print()
    {
        cout << "this = " << this << endl;
    }
};


SigleClass * SigleClass::c_instance = NULL;

SigleClass* SigleClass::GetInstance()
{
    if(c_instance == NULL)
    {
        c_instance = new SigleClass();
    }

    return c_instance;
}

int main()
{
    SigleClass* s = SigleClass::GetInstance();
    SigleClass* s1 = SigleClass::GetInstance();
    SigleClass* s2 = SigleClass::GetInstance();

    s->print();
    s1->print();
    s2->print();

    return 0;
}

运行结果:
在这里插入图片描述

实验结果:通过类的静态函数 GetInstance 创建的3个类对象的地址一样,达到预期结果



单例类模板

存在的问题

需要使用单例模式时:

  • 必须定义静态成员变量 c_instance
  • 必须定义成员函数 GetInstance

解决方案

将单例模式相关的代码抽取出来, 开发单例类
模板。当需要单例类时,直接使用单例类模板 。

实验代码
实现单例类模板

SingleTon.h
#ifndef _SINGLETON_H_
#define _SINGLETON_H_

template <typename T>
class SingleTon
{
private:
    static T* c_instance;
public:
    static T* GetInstance();
};


template <typename T>
T* SingleTon<T>::c_instance = NULL;

template <typename T>
T* SingleTon<T>::GetInstance()
{
    if(c_instance == NULL)
        c_instance = new T();

    return c_instance;
}

#endif

main.cpp

#include <iostream>
#include <string>
#include "SingleTon.h"

using namespace std;

class Test
{
public:
    void print()
    {
        cout << "this = " << this << endl;
    }
};

int main()
{
    Test* t1 = SingleTon<Test>::GetInstance();
    Test* t2 = SingleTon<Test>::GetInstance();
    Test* t3 = SingleTon<Test>::GetInstance();

    t1->print();
    t2->print();
    t3->print();

    return 0;
}

运行结果:
在这里插入图片描述

实验结果:通过单例类模板创建的对象地址都一样,达到预期。




小结

单例模式是开发中 最常用的设计模式之一
单例模式的应用使得 一个类最多只有一个对象
可以将单例模式相关的代码抽象成类模板
需要使用单例模式的灰直接使用 单例类模板

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lzg2021

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

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

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

打赏作者

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

抵扣说明:

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

余额充值