65,210
社区成员
发帖
与我相关
我的任务
分享#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;
}/*
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;
}