您的位置:首页 > 编程语言 > C语言/C++

C++单例模式的简单实现

2013-05-28 08:55 204 查看
一份好的代码就像 一个艺术,结构框架都很清晰,每个程序猿都希望自己的代码结构清晰,下面是简单的单例模式的实现

singleto.h

#include <iostream.h>

class Singleton

{

private:

Singleton();

public:

static Singleton *getInstance()

{

if(m_pThis == NULL)

{

m_pThis = new Singleton();

}

return m_pThis;

}

//内存释放,防止内存泄露

static void Release ()

{

if(m_pThis !=NULL)

{

delete m_pThis;

m_pThis = NULL;

}

}

//其他功能函数

void myOutPut()

{

cout<<"hello , I am Singleton"<<endl;

}

private:

static Singleton *m_pThis;

};

singleton.cpp

Singleton *Singleton::m_pThis = NULL;

Singleton::Singleton()

{

}

main.cpp

#include "singleton.h"

int main(int argc, char *argv[])

{

Singleton *s1 = Singleton::getInstance();

s1->myOutPut();

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: