C++单例模式模板 (简单易懂且有效)

本文介绍了如何使用C++模板简化单例模式的实现,并提供了示例代码展示如何创建和使用单例模板。通过宏定义进一步简化调用方式,同时讨论了如何通过继承和友元类防止非法实例化,确保单例模式的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例模式几乎是最常用的设计模式,简单易懂,使用起来效果显著,在此也不对单例模式做剖析,不了解的可以自行查阅资料。
项目中多次使用单例模式后发现每次都是重复的构建单例类,于是做了一个单例模式的模板。

//单例模板
//delete 与 default 来自于 c++ 11
template <typename T>
class Singleton {
    //使用默认构造和析构函数
    Singleton() = default;
    ~Singleton() = default;
public:
	//删除默认的移动、拷贝、赋值、取址
    Singleton(Singleton  &&) = delete;
    Singleton(const Singleton  &) = delete;
    void operator = (const Singleton  &) = delete;
    T *operator &() = delete;
	//获取实例,对此处有异议也可自行查阅资料
    static T* instance()
    {
        static T object;
        return &object;
    }
};

使用示例:

//测试类
class Test
{
    int id;
public:
    void setId(int id)
    {
        this->id = id;
    }
    int getId() const
    {
        return this->id;
    }
};

int main()
{
    Singleton<Test>::instance()->setId(5);
    std::cout << Singleton<Test>::instance()->getId() << std::endl;
}

如果使用的时候觉得调用太长,可以将其 #define 一下,如:

#define SingletonTest Singleton<Test>::instance()

使用时短小很多,减少自己手指的损耗,如下:

int main()
{
    SingletonTest->setId(5);
    std::cout << SingletonTest->getId() << std::endl;
}

宏定义本身是c/c++程序设计中不推荐的做法,关于宏定义是预处理期展开在此也不做赘述,个中利害还需自己斟酌。

到这里你可能会提出质疑,我们在此处并没有做到禁止创建 Test 用户类的对象,如果你有这样的需求,那请往下看.

为了禁止擅自创建 Test(用户类对象),我们改变下策略:

放开模板限制
在此不再删除取址操作(会影响返回对象的引用),取消模板类构造函数的私有化,作为基类,析构函数标记为virtual;

template <typename T>
class Singleton {
public:
    Singleton() = default;
    virtual ~Singleton() = default;
    Singleton(Singleton &&) = delete;
    Singleton(const Singleton &) = delete;
    void operator = (const Singleton &) = delete;

    static T* instance()
    {
        static T object;
        return &object;
    }
};

用户类继承单例模板
与之前不同的是,将创建对象的限制放在了用户类(即将构造函数设置为私有),构造函数私有化后,单例模板也无法创建对象,于是,将单例模板作为友元类;

class Test : public Singleton<Test>
{
    int id;
    Test() = default;
    
    //单例模板作为友元类
    friend class Singleton;
public:
    void setId(int id)
    {
        this->id = id;
    }
    int getId() const
    {
        return this->id;
    }
};

示例:

int main()
{
    //Test t;  //错误,禁止创建对象
    Test::instance()->setId(5);
    std::cout << Test::instance()->getId();
}

目前想到的方法就是这样,如有更好的的方法,还请留下宝贵的意见。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

为啥不吃肉捏

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

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

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

打赏作者

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

抵扣说明:

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

余额充值