实验5:建造者模式
[实验任务一]:计算机组装
使用建造者模式,完成下述任务:计算机组装工厂可以将CPU、内存、硬盘、主机等硬件设备组装在一起构成计算机,计算机的类型可以是笔记本,也可以是台式机。
直接放源码:
#include <iostream> using namespace std; class Computer{ public: virtual void setCpu(){}; virtual void setNc(){}; virtual void setYp(){}; virtual void setZj(){}; }; class LapComputer:public Computer{ private: string CPU=""; string nc=""; string yp=""; public: string tostring() { return "LapComputer [" + CPU + ", " + nc + ", " + yp + "]"; } void setCpu() { // TODO Auto-generated method stub CPU="CPU"; } void setNc() { // TODO Auto-generated method stub nc="内存条"; } void setYp() { // TODO Auto-generated method stub yp="硬盘"; } void setZj() { // TODO Auto-generated method stub } }; class PCComputer:public Computer{ private: string CPU=""; string nc=""; string yp=""; string zj=""; public: void setCpu() { // TODO Auto-generated method stub CPU="CPU"; } void setNc() { // TODO Auto-generated method stub nc="内存条"; } void setYp() { // TODO Auto-generated method stub yp="硬盘"; } void setZj() { // TODO Auto-generated method stub zj="主机"; } string tostring() { return "PCComputer [" + CPU + ", " + nc + ", " + yp + ", " + zj + "]"; } string getCPU() { return CPU; } void setCPU(string cPU) { CPU = cPU; } string getNc() { return nc; } void setNc(string nc) { nc = nc; } string getYp() { return yp; } void setYp(string yp) { yp = yp; } }; class Builder{ public: virtual void produceCPU(){}; virtual void produceNC(){}; virtual void ProduceYP(){}; virtual void ProduceZJ(){}; virtual Computer* build(int n){}; }; class ConcreteBuilder:public Builder{ private: Computer *cp; public: Computer* build(int t) { cout<<"正在安装... ..."<<endl; //1是笔记本 2是台式 if(t==1) { LapComputer c; cp=&c; produceCPU(); produceNC(); ProduceYP(); cout<<"笔记本安装成功"<<endl; cout<<c.tostring()<<endl; } else if(t==2) { PCComputer c; cp=&c; produceCPU(); produceNC(); ProduceYP(); ProduceZJ(); cout<<"台式电脑安装成功"<<endl; cout<<c.tostring()<<endl; } else { ; } } void produceCPU() { // TODO Auto-generated method stub cp->setCpu(); cout<<"安装CPU"<<endl; } void produceNC() { // TODO Auto-generated method stub cp->setNc(); cout<<"安装内存条"<<endl; } void ProduceYP() { // TODO Auto-generated method stub cp->setYp(); cout<<"安装硬盘"<<endl; } void ProduceZJ() { // TODO Auto-generated method stub cp->setZj(); cout<<"安装主机"<<endl; } }; int main() { int n; ConcreteBuilder b; Builder* bd=&b; cout<<"请选择你要的电脑类型 1为笔记本电脑 2位台式电脑"<<endl; cin>>n; if(n==1||n==2) { bd->build(n); }else { cout<<"请输入正确选项"<<endl; } return 0; }
标签:string,软件设计,void,nc,virtual,实验,yp,CPU From: https://www.cnblogs.com/lyf3701/p/16771947.html