最简单的单身模式

单身模式是比较常用的一种设计模式,比较简单的实现:

static HttpConnect * g_HttpConnect = 0;

HttpConnect * HttpConnect::getHttpSingler()
{
    if (g_HttpConnect == 0)
        g_HttpConnect = new HttpConnect();
    return g_HttpConnect;
}

在头文件的类中定义静态函数:

static HttpConnect * getHttpSingler();

外部调用:

HttpConnect::getHttpSingler()->setServerUrl("http://127.0.0.1:5000");

第二种方式:用模版

#ifndef SINGLETON_H
#define SINGLETON_H

#include <assert.h>

template <class T>
class Singleton
{
public:
    static T* Instance()
    {
        if(!m_Instance) m_Instance = new T;
        assert(m_Instance != NULL);
        return m_Instance;
    }
protected:
    Singleton();
    ~Singleton();
private:
    Singleton(Singleton const&);
    Singleton& operator=(Singleton const&);
    static T* m_Instance;
};

template <class T> T* Singleton<T>::m_Instance=NULL;

#endif // SINGLETON_H

在HttpConnect 类头文件中申明:

typedef Singleton<HttpConnect> HttpSingle;

外部调用:

HttpSingle::Instance()->.....
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值