单例模式案例 主席
- 目的为了让类中只有一个实例,实例不需要自己释放
- 将默认构造和拷贝构造私有化
- 内部维护一个 对象指针
- 私有化唯一指针
- 对外提供 getInstance 方法来访问这个指针
- 保证类中只能实例化一个对像
-
#define _CRT_SECURE_ND_WARNINGS #include<iostream> using namespace std; //创建主席类 //需求:单例模式 为了创建类中的对象,并保证只有一个对象实例 class ChairMan { //1.构造函数 进行私有化 private: ChairMan() { // cout << "国家" << endl; } //拷贝构造私有化 ChairMan(const ChairMan&c) { } public: //提供 get方法 访问主席 static ChairMan* getInstance() { return singleMan; } private: static ChairMan* singleMan; }; ChairMan* ChairMan::singleMan = new ChairMan; void text01() { ChairMan*cm1=ChairMan::getInstance(); ChairMan* cm2 = ChairMan::getInstance(); if (cm1 == cm2) { cout << "cm1与cm2相同" << endl; } else { cout << "不同" << endl; } } int main() { cout << "main diaoyong" << endl;//国家先于main调用 text01(); system("pause"); return EXIT_SUCCESS; }
#define _CRT_SECURE_ND_WARNINGS #include<iostream> #include<string> using namespace std; class Printer { private: Printer() { m_Count = 0; }; Printer(const Printer& p); public: static Printer* getInstance() { return singlePrinter; } void printText(string text) { cout << text << endl; m_Count++; cout << "打印机使用次数" << m_Count<<endl; } private: static Printer* singlePrinter; int m_Count; }; Printer*Printer::singlePrinter = new Printer; void text01() { //拿到打印机 Printer* printer = Printer::getInstance(); printer->printText("高职"); printer->printText("退休"); printer->printText("高职"); printer->printText("高职"); } int main() { text01(); system("pause"); return EXIT_SUCCESS; }
打印机
- 类似主席案例
- 提供打印功能和统计打印次数功能