C++实现设计模式: Singleton 单例模式

本文深入探讨了C++中Singleton模式的设计与实现,通过具体的代码示例解释了Singleton模式的工作原理,并介绍了如何确保线程安全地创建单例对象。

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


注:
又一次仔细读了刘未鹏写的《暗时间》,总结自己之所以在编程方面成长不理想的原因就是自己花在总结上的时间太少了,总是写过的代码和用过的模式很快就忘记了,有点过分依赖参考资料和Google.
因此,今天起陆续总结一下自己使用过的一些设计模式,不过由于C++设计模式方面的资料很少,我将坚持采用C++语言说明。
目前自己能够熟练使用的模式大概有:Singleton, Factory,Adapter, Proxy, Facade,Observer, Decorator,Strategy, Template。


第一回:Singleton 

SingletonExecutor.h
class SingletonExecutor
{
private:
    SingletonExecutor();
    ~SingletonExecutor();
    SingletonExecutor(const SingletonExecutor&);
    SingletonExecutor& operator=(const SingletonExecutor&);
public:
    static SingletonExecutor& GetInstance();
}

SingletonExecutor.cpp
SingletonExecutor& SingletonExecutor::GetInstance()
{
    static SingletonExecutor* sInstance = NULL;
    if ( !sInstance)
    {
        Mutex mutex;
        ScopedLock(&mutex);
        if (!sInstance)
        {
            sInstance = new SingletonExecutor();
        }
    }
    return *sInstance;
}

//In fect use the default constructor is OK.
SingletonExecutor::SingletonExecutor(void)
{
     //
}

//There is no need destructor because the singleton object should exist throughout the program life cycle.


Announce in advance:
下期博客,敬请期待:
设计模式前传  之 你所不知道的构造函数

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值