单例模式

本文深入探讨了单例模式的三大要点,并通过C++代码示例详细展示了单例模式的实现过程,包括实例创建、实例获取及资源释放。
/****单例模式要点:
一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。
***/

#include <iostream>
using namespace std;

class CSingleton
{
    public:
    static CSingleton * GetInstance()
    {
        if(NULL == m_pInstance)
            m_pInstance = new CSingleton();
        return m_pInstance;
    }
    static void Release()   //必须,否则会导致内存泄露
    {
        if(NULL != m_pInstance)
        {
            delete m_pInstance;
            cout<<"this is CSingleton::Release()"<<endl;
            m_pInstance = NULL;
        }
    }

    protected:
        CSingleton()
        {
            cout<<"CSingleton"<<endl;
        };
        static CSingleton * m_pInstance;
};

CSingleton* CSingleton::m_pInstance = NULL;
/***
class CSingleDraw:public CSingleton
{
public:
    static CSingleDraw* GetInstance()
    {
        if(NULL == m_pInstance)
            m_pInstance = new CSingleDraw();
        return (CSingleDraw*)m_pInstance;
    }
protected:
    CSingleDraw()
    {
        cout<<"CSingleDraw"<<endl;
    }
};
***/
int main()
{
   // CSingleDraw* s1 = CSingleDraw::GetInstance();
   // CSingleDraw* s2 = CSingleDraw::GetInstance();
    CSingleton *s1=CSingleton::GetInstance();
    CSingleton *s2=CSingleton::GetInstance();
    s2->Release(); //this is CSingleton::Release()
    s1->Release();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值