设计一个简单的单例模式 源代码
#include <iostream>
#include <string>
using namespace std;
class Printer
{
public:
//2提供一个方法获得单例指针
static Printer* getSinglePrint(void)
{
return singlePrint;
}
//4设置函数功能(自定义部分)
void printText(char* str)
{
cout << "打印" << str <<endl;
count ++;
}
int count;
private:
//1定义一个静态的对象指针变量,保存唯一实例地址
static Printer *singlePrint;
private:
//3防止该类实例化其他对象,将整个构造函数全部私有
Printer(){count = 0;}
Printer(const Printer &ob){}
};
Printer *Printer::singlePrint = new Printer;
int main()
{
Printer *p1 = Printer::getSinglePrint();
p1->printText("入职报告");
p1->printText("体检报告");
p1->printText("离职证明");
Printer *p2 = Printer::getSinglePrint();
p2->printText("入职报告");
p2->printText("体检报告");
p2->printText("离职证明");
cout << "打印任务数量:" << p2->count<<endl;
return 0;
}