• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
戈瑾
博客园    首页    新随笔    联系   管理    订阅  订阅
单例模式——C++实现

问题描述:

使用建造者模式,完成下述任务:计算机组装工厂可以将CPU、内存、硬盘、主机等硬件设备组装在一起构成计算机,计算机的类型可以是笔记本,也可以是台式机。

类图:

C++源代码:

#include<iostream>
#include<string>
using namespace std;
//单例角色——StudentNo类
class StudentNo{
private:
	static StudentNo* instance;
	string no;
	StudentNo(){}
	void setStudentNo(string n){
		no=n;
	}
public:
	static StudentNo* getInstance(){
		if(instance==NULL){
			cout<<"第一次注册,分配新的学号"<<endl;
			instance=new StudentNo();
			instance->setStudentNo("20194024");
		}else{
			cout<<"重复注册,获取旧的学号"<<endl;
		}
		return instance;
	}
	string getStudentNo(){
		return no;
	}
};
StudentNo* StudentNo::instance=NULL;
int main(){
	StudentNo *x,*y;
	x=StudentNo::getInstance();
	y=StudentNo::getInstance();
	cout<<"学号是否一致";
	if(x==y){
		cout<<"true"<<endl;
	}

	string a,b;
	a=x->getStudentNo();
	b=y->getStudentNo();
	cout<<"第一次学号是"<<a<<endl;
	cout<<"第二次学号是"<<b<<endl;
	cout<<"内容是否相等";
	if(strcmp(a.c_str(),b.c_str())==0){
		cout<<"true"<<endl;
	}
	cout<<"是否是相同对象";
	if(a==b){
		cout<<"true"<<endl;
	}
	return 0;
}

  

运行结果:

 

posted on 2021-09-29 22:11  戈瑾  阅读(95)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3