C++ 单例模式 demo

//单例模式


/*
一是某个类只能有一个实例;
二是它必须自行创建这个实例;
三是它必须自行向整个系统提供这个实例,单例对象持有对自己的引用;
*/


#include "string.h"
#include "iostream.h"




class SingletonClass
{
private:
	static SingletonClass instance;
	char Classname[30];
	SingletonClass()
	{
		cout<<"!!!!!"<<endl;//调用构造函数的标记
		strcpy(Classname, "SingletonClass");
	}
	SingletonClass(SingletonClass &instance)
	{
		cout<<"~~~~~~~~"<<endl;//调用拷贝构造函数的标记
		strcpy(instance.Classname,this->Classname);
	}
public:
	char *getClassName()
	{
		return Classname;
	}
	static SingletonClass& getInstance()
	{
		return instance;//返回对象时调用拷贝构造函数
	}
	void setClassName(char *p)
	{
		strcpy(Classname, p);
	}
};


SingletonClass SingletonClass::instance;


int main(int argc, char *argv[])
{
	SingletonClass *p = &SingletonClass::getInstance();//获取实例的指针
	cout<<"class name:"<<p->getClassName()<<endl;
	p->setClassName("123456");
	cout<<"class name:"<<p->getClassName()<<endl;
	cout<<"--------------------------------------------"<<endl;
    
	SingletonClass *p1 = &SingletonClass::getInstance();//再次获取实例的指针
	cout<<"class name:"<<p1->getClassName()<<endl;//输出123456
	cout<<"class name:"<<p->getClassName()<<endl;//如果函数不反回引用,则输出SingletonClass(临时对象)


	cout<<"--------------------------------------------"<<endl;
	cout<<"p:"<<p<<"p1:"<<p1<<endl;


	return 0;
}


你可能感兴趣的:(C++)