C++单例模式实例

C++单例模式
别人教的实例,我手写了一下

实例1 众人使用一台打印机
#pragma once
#include<iostream>
#include<string>

class Printer {
private:
	Printer() { m_cout = 0; }
	Printer(const Printer& p);
	int m_cout;
	static Printer* sigleprinter;
public:
	static Printer* getInstance() {
		return sigleprinter;
	}
	void PrintTex(std::string text) {
		std::cout << text << std::endl;
		m_cout++;
		std::cout << "打印机使用的次数为:" << std::endl;
	}
};

Printer* Printer::sigleprinter = new Printer;

void test01() {
	Printer * rinter = Printer::getInstance();

	rinter->PrintTex("1次报告");
	rinter->PrintTex("2次报告");
	rinter->PrintTex("3次报告");
	rinter->PrintTex("4次报告");
}

int main() {

	test01();


	system("pause");
	return EXIT_SUCCESS;
}
实例2 指定的某一个人
#pragma once
#include<iostream>

using namespace std;

class Chairman {
private:
	//Chairman() {}
	Chairman() {
		cout << "创建对象" << endl;
	}
	Chairman(const Chairman&c) {}
public:
	static Chairman* getInstance() {
		return Singleman;
	}
private:
	static Chairman * Singleman;
};
Chairman * Chairman::Singleman = new Chairman;

void test01() {
	Chairman* Chairman1 = Chairman::getInstance();
	Chairman* Chairman2 = Chairman::getInstance();

	if (Chairman1 == Chairman2) {
		cout << "1,2两者相同" << endl;
	}
	else cout << "1,2两者不同" << endl;

/*	Chairman* Chairman3 = new Chairman(*Chairman2);
	if (Chairman3 == Chairman2) {
		cout << "2,3两者相同" << endl;
	}
	else cout << "2,3两者不同" << endl;
	*/
}

int main() {

	test01();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值