设计模式-------Singleton模式

本文深入探讨了单例模式的实现细节,通过宏实现优化了代码结构,确保了资源的有效管理,并解决了内存泄漏问题。同时,文章强调了在实际应用中考虑线程安全的重要性。

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

Singleton是全局变量的一种取代策略。

意图: 保证一个类仅有一个实例,并提供一个访问它的全局访问点。

实现:

Singleton.h:

class Singleton{
public:
    static Singleton* Instance();

    int TestFunc() {return 1;}

protected:
    Singleton(){};    // 构造函数protected,可以防止外部代码创建Singleton实

例

private:
    static Singleton* _instance;
};


Singleton.cpp:

#include "Singleton.h"

Singleton*  Singleton::_instance = 0;

Singleton*  Singleton::Instance()
{
    if (0 == _instance)
        _instance = new Singleton;

    return _instance;
}



通常在实际项目中,会用一个更通用的方法来代替每个单例中的重复代码,比如:

宏实现:

Singleton.h:

// 宏实现
#define DECLEAR_SINGLETON(class_name)   \
static class_name* Instance()           \
{                                       \
    static class_name* _instance = 0;   \
    if (0 == _instance)                 \
        _instance = new class_name;     \
    return _instance;                   \
}               


class Singleton{
public:
    DECLEAR_SINGLETON(Singleton)

    int TestFunc(){return 1;}
protected:
    Singleton(){} 
};



Singleton.cpp里无须和单例有关的代码


上述实现的问题是 _instance是new出来的,但是无明确调用delete的地方,虽然程序退出后会回收该空间,但如果析构函数中有其它操作,则无法调用。修正如下:

#define DECLEAR_SINGLETON(class_name)   \
static class_name* Instance()           \
{                                       \
    static class_name _instance;        \
    return &_instance;                  \
}


其特点是:

1. static 成员是在首次调用时创建的(因此这个单例模式满足惰性创建,即第一次使用时才创建);

2. 程序运行完后会调用static成员的析构函数并回收static成员的空间(因此程序结束时会调用析构函数);

3. 未考虑线程安全。


完整代码:

#define DECLEAR_SINGLETON(class_name)   \
static class_name* Instance()           \
{                                       \
    static class_name _instance;        \
    return &_instance;                  \
}

class A{
public:
    DECLEAR_SINGLETON(A)

    ~A() { printf ("decreate A\n");}
    void test() {printf ("testtt\n");}
private:
    A(){ printf ("create A\n");}

};

int main()
{
    printf ("start test\n");

    A::Instance()->test();

    printf ("end test \n");
}


输出:

start test
create A
testtt
end test
decreate A



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值