编译环境VS2012。如题用C++实现单例模式,代码如下。
#ifndef SINGLETON_H
#define SINGLETON_H
#endif
#ifndef _IOSTREAM_
#include <iostream>
#endif
#ifndef _STRING_
#include <string>
#endif
#ifndef _WINDOWS_
#include <windows.h>
#endif
using namespace std;
class Singleton
{
private:
std::string value;
static Singleton* instance;
Singleton(){};
public:
static Singleton* getInstance();
std::string getValue();
void setValue(char*);
~Singleton();
};
Singleton* Singleton::instance = new Singleton;
Singleton* Singleton::getInstance()
{
return instance;
}
string Singleton::getValue()
{
return this->value;
}
void Singleton::setValue(char* _value)
{
this->value.assign(_value);
}
Singleton::~Singleton()
{
instance = NULL;
delete instance;
}
int main(int __argc, char **__argv)
{
Singleton* aaa = Singleton::getInstance();
cout<<"Before set aaa value, aaa->value:\t"<<aaa->getValue()<<endl;
aaa->setValue("bye 2012");
cout<<"After set aaa value, aaa->value:\t"<<aaa->getValue()<<endl;
Singleton* bbb = Singleton::getInstance();
cout<<"Before set bbb value, bbb->value:\t"<<bbb->getValue()<<endl;
bbb->setValue("hello 2013");
cout<<"After set bbb value, bbb->value:\t"<<bbb->getValue()<<endl;
cout<<"After set bbb value, aaa->value:\t"<<aaa->getValue()<<endl;
Sleep(5000);
return 0;
}