肆-拾陆|单例模式的两个案例

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//单:唯一 只有一个 例:实例
//主席类
/*
class 类名
{
	private:
	构造函数
	拷贝构造函数
	静态成员
	public:
	静态成员只读函数
}
类名*类名::静态成员=new 类名;

*/
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 << "main函数调用" << endl;
//编译阶段构造打印机,然后再用main函数。

	test01();

	system("pause");
	return EXIT_SUCCESS;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值