这个类只能实例化出一个对象

  • 单例模式 – 主席类案例
  • 通过一个类 只能实例化唯一的一个对象
  • 私有化
  • 默认构造
  • 拷贝构造
  • 唯一实例指针
  • 对外提供 getInstance 接口,将指针返回
  • 单例模式 – 打印机案例
  • 和主席类案例一样设计单例模式
    提供打印功能并且统计打印次数
  1. 不能实例化对象,将构造函数私有化,不可以创建对象
  2. 需要提供一个类(静态),所有变量对应的是一个东西,将指针 私有化,对外提供只读接口,唯一实例指针
  3. 不能克隆类,也就是不能拷贝构造

单例模式-主席类案例

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

//主席类
class ChairMan
{
public:
    static ChairMan * getInstacne()
	{
		return singleMan;
	}
private:
	//将构造函数私有化,不可以创建多个对象
	ChairMan(){};

	ChairMan(const ChairMan &){};

//public:
private:
	//将主席指针 私有化,对外提供只读接口
	static  ChairMan * singleMan; //类内声明  类外初始化
};

ChairMan *  ChairMan::singleMan = new ChairMan;

void test01()
{
	/*ChairMan c1;
	ChairMan c2;
	ChairMan * c3 = new ChairMan;*/

	//ChairMan * c1 = ChairMan::singleMan;
	//ChairMan * c2 = ChairMan::singleMan;


	ChairMan * c1 = ChairMan::getInstacne();
	ChairMan * c2 = ChairMan::getInstacne();

	//ChairMan * c3 = new ChairMan(*c1);

	if (c1 == c2)
	{
		cout << "c1 = c2" << endl;
	}
	else
	{
		cout << "c1 != c2" << endl;
	}

	//if (c1 == c3)
	//{
	//	cout << "c1 = c3" << endl;
	//}
	//else
	//{
	//	cout << "c1 != c3" << endl;
	//}


}


int main(){
	test01();


	system("pause");
	return EXIT_SUCCESS;
}

单例模式 - 打印机案例

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include <string>
class Printer
{
public:
	static Printer * getInstance()
	{
		return printer;
	}

	void printText(string text)
	{
		m_Count++;
		cout << text << endl;
	}

	int m_Count;

private:

	Printer()
	{ 
		m_Count = 0;
		//cout << "打印机构造调用" << endl; 
	};

	Printer(const Printer & p){};

	static Printer * printer;

	
};

Printer * Printer::printer = new Printer;


void test01()
{
	Printer * p1 = Printer::getInstance();
	p1->printText("入职证明");
	p1->printText("离职证明");
	p1->printText("加薪申请");
	p1->printText("旅游申请");

	cout << "打印机使用次数: " << p1->m_Count << endl;


	Printer * p2 = Printer::getInstance();
	p2->printText("调休申请");

	cout << "打印机使用次数: " << p1->m_Count << endl;

}

int main(){
//	cout << "mian函数调用" << endl;

	test01();

	system("pause");
	return EXIT_SUCCESS;
}