#include<iostream> #include<string> using namespace std; //产品类——Computer类 class Computer{ private: string CPU; string RAM; string Hard; string Host; public: string getCPU(){ return CPU; } string getRAM(){ return RAM; } string getHard(){ return Hard; } string getHost(){ return Host; } void setCPU(string cpu){ CPU=cpu; } void setRAM(string ram){ RAM=ram; } void setHard(string hard){ Hard=hard; } void setHost(string host){ Host=host; } }; //抽象建造者类——ComputerBuilder类 class ComputerBuilder{ protected: Computer computer; public: virtual void buildCPU()=0; virtual void buildRAM()=0; virtual void buildHard()=0; virtual void buildHost()=0; Computer getComputer(){ return computer; } }; //具体建造者类——LaptopComputerBuilder类 class LaptopComputerBuilder:public ComputerBuilder{ public: void buildCPU() { computer.setCPU("安装笔记本CPU"); } void buildRAM() { computer.setRAM("安装笔记本内存"); } void buildHard() { computer.setHard("安装笔记本硬盘"); } void buildHost() { computer.setHost("安装笔记本主机"); } }; //具体建造者类——DesktopComputerBuilder类 class DesktopComputerBuilder:public ComputerBuilder{ public: void buildCPU() { computer.setCPU("安装台式机CPU"); } void buildRAM() { computer.setRAM("安装台式机内存"); } void buildHard() { computer.setHard("安装台式机硬盘"); } void buildHost() { computer.setHost("安装台式机主机"); } }; //指挥者类——Director类 class Director{ private: ComputerBuilder* cb; public: void setComputerBuilder(ComputerBuilder *c){ cb=c; } Computer construct(){ cb->buildCPU(); cb->buildRAM(); cb->buildHard(); cb->buildHost(); return cb->getComputer(); } }; //测试类 int main(){ ComputerBuilder* cb=NULL; int i; cout<<"请选择:1.笔记本 2、台式机"<<endl; cin>>i; if(i==1){ cb=new LaptopComputerBuilder(); }else if(i==2){ cb=new DesktopComputerBuilder(); }else{ cout<<"输入无效!"; } Director* dir=new Director(); dir->setComputerBuilder(cb); Computer computer=dir->construct(); cout<<"计算机组成:"<<endl; cout<<computer.getCPU()<<endl; cout<<computer.getRAM()<<endl; cout<<computer.getHard()<<endl; cout<<computer.getHost()<<endl; delete cb; delete dir; return 0; }
标签:ComputerBuilder,string,cb,void,建造,模式,computer,public From: https://www.cnblogs.com/qiuyutingyyds/p/16774378.html