多态案例三 —— 电脑组装
电脑主要组成部件为CPU(用于计算),显卡(用于显示),内存条(用于存储)
将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商
创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作
//每个零件的抽象类
class CPU
{
public :
virtual void Calculate() = 0;
};
class GPU
{
public :
virtual void Display() = 0;
};
class RAM
{
public :
virtual void Storage() = 0;
};
//Inter厂商的零件
class InterCPU : public CPU
{
public:
void Calculate()
{
cout << "Inter的CPU开始计算" << endl;
}
};
class InterGPU : public GPU
{
public :
void Display()
{
cout << "Inter的GPU开始显示" << endl;
}
};
class InterRAM : public RAM
{
public :
void Storage()
{
cout << "Inter的RAM开始存储" << endl;
}
};
//Lenovo厂商的零件
class LenovoCPU : public CPU
{
public:
void Calculate()
{
cout << "Lenovo的CPU开始计算" << endl;
}
};
class LenovoGPU : public GPU
{
public:
void Display()
{
cout << "Lenovo的GPU开始显示" << endl;
}
};
class LenovoRAM : public RAM
{
public:
void Storage()
{
cout << "Lenovo的RAM开始存储" << endl;
}
};
//电脑类
class Computer
{
private :
CPU* m_CPU; //抽象类不能实例化,但是可以利用指针指向子类对象
GPU* m_GPU;
RAM* m_RAM;
public :
Computer(CPU* cpu, GPU* gpu, RAM* ram)
{
m_CPU = cpu;
m_GPU = gpu;
m_RAM = ram;
}
~Computer()
{
if (m_CPU != NULL)
{
delete m_CPU;
m_CPU = NULL;
}
if (m_GPU != NULL)
{
delete m_GPU;
m_GPU = NULL;
}
if (m_RAM != NULL)
{
delete m_RAM;
m_RAM = NULL;
}
}
void DoWork()
{
m_CPU->Calculate();
m_GPU->Display();
m_RAM->Storage();
}
};
void test53()
{
Computer c1(new InterCPU, new InterGPU, new InterRAM);
c1.DoWork();
cout << "-----------------------" << endl;
Computer *c2 = new Computer(new LenovoCPU, new LenovoGPU, new LenovoRAM);
c2->DoWork();
delete c2;
c2 = NULL;
cout << "-----------------------" << endl;
CPU* cpu = new InterCPU;
GPU* gpu = new InterGPU;
RAM* ram = new InterRAM;
Computer c3(cpu, gpu, ram);
c3.DoWork();
cout << "-----------------------" << endl;
CPU* cpu2 = new InterCPU;
GPU* gpu2 = new InterGPU;
RAM* ram2 = new InterRAM;
Computer *c4 = new Computer(cpu2, gpu2, ram2);
c4->DoWork();
delete c4;
c4 = NULL;
}
void main53()
{
test53();
system("pause");
}
(哔哩哔 哩黑马程序员 C++教程 学习笔记,如有侵权请联系删除)