用C++实现一个奇怪的类!!

c562731235 2011-11-30 10:32:14
有 一个类,在整个应用程序中有且只能有一个实例,并提供一个访问它的全局访问点(Singleton模 式)。请用C++来 实现这样的一个类。
...全文
75 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
pathuang68 2011-11-30
  • 打赏
  • 举报
回复
Singleton通常有以下特点:
1. 构造方法是private的;
2. 有一个private的静态变量,其类型就是Singleton本身;
3. 有一个public的方法getInstance(),其返回类型是Singleton;
4. 要考虑线程安全问题

可以参考拙作:
C++实现Singleton模式
turing-complete 2011-11-30
  • 打赏
  • 举报
回复
#include <iostream>

using std::cout;
using std::endl;

class Myjob
{
public:

static Myjob* GetInstance(int a, int b);

static void dispose(void);

void show(void);

private:

int x1, x2;

Myjob(int a, int b);

~Myjob();

static Myjob *m_pInstance;
};

// 单例初始化
Myjob* Myjob::m_pInstance(NULL);

Myjob::Myjob(int a, int b) : x1(a), x2(b)
{

}

Myjob::~Myjob(void)
{

}

// 释放资源
void Myjob::dispose(void)
{
if (Myjob::m_pInstance != NULL)
{
delete Myjob::m_pInstance;
Myjob::m_pInstance = NULL;
}
}

Myjob* Myjob::GetInstance(int a, int b)
{
if (m_pInstance == NULL)
{
m_pInstance = new Myjob(a, b);
}
return m_pInstance;
}

void Myjob::show(void)
{
cout << this->x1 << " " << this->x2 << endl;
}

int main()
{
Myjob *instance(Myjob::GetInstance(1, 2));
instance->show();
Myjob::dispose();// 不过单例一般很少涉及释放代码
return 0;
}
rendao0563 2011-11-30
  • 打赏
  • 举报
回复
单件实现有太多种了. 目前市面上的应该是boost的那套实现最好.
对象 2011-11-30
  • 打赏
  • 举报
回复
/*
Creational Pattern: SINGLETON
Author: Rajesh V.S
Language: C++
Email: rajeshvs@msn.com
*/

#include <iostream>


using namespace std;

class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor

}
public:
static Singleton* getInstance();
void method();
~Singleton()
{
instanceFlag = false;
}
};

bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}

void Singleton::method()
{
cout << "Method of the singleton class" << endl;
}

int main()
{
Singleton *sc1,*sc2;
sc1 = Singleton::getInstance();
sc1->method();
sc2 = Singleton::getInstance();
sc2->method();

return 0;
}


来源:http://www.codeproject.com/KB/cpp/singletonrvs.aspx
xxweilw 2011-11-30
  • 打赏
  • 举报
回复
Singleton模式在网上好多的,不知道你想问啥
無_1024 2011-11-30
  • 打赏
  • 举报
回复
这个貌似很熟悉 但是记不起来了

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧