Singleton Pattern Analysis

11. Singleton case ---- Chairman
(1) Internal maintain a static object pointer of privatization. (Outside the class initialization, compiling stage new came out, predates the implementation of the main function of the ratio)
(2) default constructor and copy constructor privatization
(3) provide external public of static getInstance () method to access this pointer
Note: Purpose: to give one example, there is a class, instance do not need to release (i.e., no need to provide their own destructor)

Case a chairman

#include <iostream>
#include<string>
using namespace std;

class ChairMan
{
public:
	static ChairMan *getInstance()
	{
		return singleMan;
	}
private:
	static ChairMan * singleMan;//私有静态唯一对象指针
	ChairMan()
	{
		cout<<"ChairMain 构造函数的调用"<<endl;
	}
	ChairMan(const ChairMan* &C){}
};

ChairMan * ChairMan::singleMan = new ChairMan;//static类外初始化

void test01()
{
	cout<<"main函数的调用"<<endl;//证明对象先于main函数出现
	ChairMan* c1=ChairMan::getInstance();
	ChairMan* c2=ChairMan::getInstance();
	if(c1 == c2)
	{
		cout<<"c1,c2相同"<<endl;
	}
}
Published 38 original articles · won praise 13 · views 4346

Guess you like

Origin blog.csdn.net/YanWenCheng_/article/details/103924962