首页 > 编程语言 >c++从入门到精通——单例模式

c++从入门到精通——单例模式

时间:2022-11-01 18:34:09浏览次数:45  
标签:Printer 入门 getInstance c++ singleMan static ChairMan 单例 new


声明无法直接调用

#define _CRT_SECURE_NO_WARNINGS

#include<iostream>

using namespace std;

class ChairMan {
public:
static ChairMan *getInstance() {
return singleMan;
}
private:
ChairMan() { };
ChairMan(const ChairMan &){};
static ChairMan *singleMan;
};
ChairMan * ChairMan::singleMan = new ChairMan;
void test01(){
/* 无法调用函数
ChairMan c1;
ChairMan c2;
ChairMan *c3 = new ChairMan;*/


}
int main() {
test01();
// system("pause");
return EXIT_SUCCESS;
}

单例模式获取

#define _CRT_SECURE_NO_WARNINGS

#include<iostream>

using namespace std;

class ChairMan {
public:
static ChairMan *getInstance() {
return singleMan;
}
private:
ChairMan() { };
ChairMan(const ChairMan &){};
static ChairMan *singleMan;
};
ChairMan * ChairMan::singleMan = new ChairMan;
void test01(){
/* 无法调用函数
ChairMan c1;
ChairMan c2;
ChairMan *c3 = new ChairMan;
ChairMan *c1 = ChairMan::singleMan;*/
ChairMan *c1 = ChairMan::getInstance();
ChairMan *c2 = ChairMan::getInstance();
//ChairMan *c3 = new ChairMan(*c1);
if(c1==c2){
cout<<"c1=c2"<<endl;
} else{
cout<<"c1!=c2"<<endl;
}


}
int main() {
test01();
// system("pause");
return EXIT_SUCCESS;
}

c++从入门到精通——单例模式_单例模式

打印机案例

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Printer{
public:
int m_Count{0};
static Printer* getInstance(){
return printer;
}
void printText(string text){
m_Count++;
cout<<"m_Count,打印机被调用"<<endl;
};
private:
static Printer *printer;
Printer(){
m_Count=0;
}
Printer(const Printer&p){};
};
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();
p1->printText("还是入职证明");
cout<<"打印机使用次数"<<p1->m_Count<<endl;



}
int main() {
test01();
// system("pause");
return EXIT_SUCCESS;
}

c++从入门到精通——单例模式_开发语言_02


标签:Printer,入门,getInstance,c++,singleMan,static,ChairMan,单例,new
From: https://blog.51cto.com/u_13859040/5814691

相关文章