/*C++单例模式的实现*/
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton* getInstance();//一个类方法,返回Single类型指针
void setValue(int);
int getValue();
~Singleton();
private:
Singleton();//构造函数私有
static Singleton* instance;//唯一一个实例
int value;
};
Singleton* Singleton::instance=NULL;//必须类外定义初值NULL
Singleton* Singleton::getInstance()
{
if (NULL==instance)
{
instance=new Singleton();
}
return instance;
}
Singleton::Singleton()
{
this->value=100;
cout<<"Singleton Constructor!!!"<<endl;
}
Singleton::~Singleton()
{
cout<<"Singleton Destructor!!!"<<endl;
}
int Singleton::getValue()
{
return this->value;
}
void Singleton::setValue(int v)
{
value=v;
}
//测试程序
int main()
{
Singleton* s1=Singleton::getInstance();
Singleton* s2=Singleton::getInstance();
if(s1==s2)
cout<<"s1,s2相等,并指向唯一一个单例实例"<<endl;
cout<<"s1指向的实例的value等于"<<s1->getValue()<<endl;
cout<<"s2指向的实例的value等于"<<s2->getValue()<<endl;
s1->setValue(200);
cout<<"s1指向的实例的value等于"<<s1->getValue()<<endl;
cout<<"s2指向的实例的value等于"<<s2->getValue()<<endl;
delete Singleton::getInstance();
return 0;
}
C++单例模式实现
最新推荐文章于 2024-10-15 15:11:19 发布