1. 需求
电脑主要组成部件为 CPU(用于计算),显卡(用于显示),内存条(用于存储)
将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商
创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作
2. 整体架构流程
#include <iostream>
using namespace std;
class CPU{
public:
virtual void calculate() = 0;
};
class GPU{
public:
virtual void display() = 0;
};
class Memory{
public:
virtual void storage() = 0;
};
class InterCPU:public CPU{
public:
void calculate() override {
cout << "Inter CPU" << endl;
}
};
class InterGPU:public GPU{
public:
void display() override {
cout << "Inter GPU" << endl;
}
};
class InterMemory:public Memory {
public:
void storage() override {
cout << "Inter Memory" << endl;
}
};
class LenovoCPU:public CPU{
public:
void calculate() override {
cout << "Lenovo CPU" << endl;
}
};
class LenovoGPU:public GPU{
public:
void display() override {
cout << "Lenovo GPU" << endl;
}
};
class LenovoMemory:public Memory {
public:
void storage() override {
cout << "Lenovo Memory" << endl;
}
};
class Computer {
public:
Computer(CPU *cpu, GPU *gpu, Memory *memory) {
m_cpu = cpu;
m_gpu = gpu;
m_mem = memory;
}
void doWork() {
m_cpu->calculate();
m_gpu->display();
m_mem->storage();
}
~Computer() {
if (m_cpu != nullptr) {
delete m_cpu;
m_cpu = nullptr;
}
if (m_gpu != nullptr) {
delete m_gpu;
m_gpu = nullptr;
}
if (m_mem != nullptr) {
delete m_mem;
m_mem = nullptr;
}
}
private:
CPU *m_cpu; // 不能写 CPU cpu = new Inter; 因为纯虚函数无法实例化
GPU *m_gpu;
Memory *m_mem;
};
void test01() {
// 第一台电脑
Computer(new InterCPU, new LenovoGPU, new InterMemory).doWork();
// 第二台电脑
auto inter_cpu = new InterCPU; // auto可以代替原重复的函数名InterCPU
auto inter_gpu = new InterGPU;
auto inter_mem = new InterMemory;
Computer(inter_cpu, inter_gpu, inter_mem).doWork();
// 第三台电脑
CPU *lenovo_cpu = new LenovoCPU; // 但是可以写纯虚函数的指针指向new子类
GPU *lenovo_gpu = new LenovoGPU;
Memory *lenovo_memory = new LenovoMemory;
auto *computer = new Computer(lenovo_cpu, lenovo_gpu, lenovo_memory);
computer->doWork();
delete computer;
}
int main()
{
// 多态案例:电脑组装
test01();
// system("pause");
return 0;
}
3. 输出
Inter CPU
Lenovo GPU
Inter Memory
Inter CPU
Inter GPU
Inter Memory
Lenovo CPU
Lenovo GPU
Lenovo Memory

126

被折叠的 条评论
为什么被折叠?



