建造者模式

[实验任务一]:计算机组装

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

实验要求:

1. 画出对应的类图;

 

2.提交源代码;

#include<iostream>

using namespace std;

#include<string>

 

class Computer

{

private:

string host;      //主机

string internal;  //内存

string harddisk;  //硬盘

public:

void setHost(string host)

{

this->host = host;

}

void setInternal(string internal)

{

this->internal = internal;

}

void setHarddisk(string harddisk)

{

this->harddisk = harddisk;

}

string getHost()

{

return host;

}

string getInternal()

{

return internal;

}

string getHarddisk()

{

return harddisk;

}

};

 

class ComputerBuilder

{

public:

virtual void buildHost()=0;

virtual void buildInternal()=0;

virtual void buildHarddisk()=0;

Computer getComputer()

{

return computer;

}

protected:

Computer computer;

};

 

class Desktop : public ComputerBuilder

{

public:

 

void buildHost()

{

computer.setHost("台式机主机");

}

 

void buildInternal()

{

computer.setInternal("台式机内存");

}

 

void buildHarddisk()

{

computer.setHarddisk("台式机硬盘");

}

 

};

 

class Laptop : public ComputerBuilder

{

public:

 

void buildHost()

{

computer.setHost("笔记本主机");

}

 

void buildInternal()

{

computer.setInternal("笔记本内存");

}

 

void buildHarddisk()

{

computer.setHarddisk("笔记本硬盘");

}

 

};

 

class Worker

{

private:

ComputerBuilder *cb;

public:

void setComputerBuilder(ComputerBuilder *cb)

{

this->cb = cb;

}

Computer construct()

{

cb->buildHost();

cb->buildInternal();

cb->buildHarddisk();

return cb->getComputer();

}

};

 

int main()

{

string t;

cout << "请输入电脑类型:";

cin >> t;

Worker *worker = new Worker();

if (!t.compare("Desktop")) {

ComputerBuilder * cb = new Desktop();

worker->setComputerBuilder(cb);

 

}

else

{

ComputerBuilder * cb = new Laptop();

worker->setComputerBuilder(cb);

}

Computer  computer = worker->construct();

cout << "部件组成:" << endl;

cout << computer.getHost() << endl;

cout << computer.getInternal() << endl;

cout << computer.getHarddisk() << endl;

}

3. 注意编程规范。

 

 

posted @ 2021-09-19 23:28  Zwyooo  阅读(63)  评论(0编辑  收藏  举报