利用多态实现计算机组转流程:
polymorphic -> 多态
基础零件(抽象类):
class CPU
{
public:virtual void calculate() = 0;
};
class VideoCard
{
public:virtual void display() = 0;
};
class Memory
{
public:virtual void storage() = 0;
};
电脑主体:
class Computer
{
public:Computer(CPU* cpu, VideoCard* vc, Memory* mem){m_cpu = cpu, m_vc = vc, m_mem = mem;}~Computer(){if (m_cpu != NULL){delete m_cpu;m_cpu = NULL;}if (m_vc != NULL){delete m_vc;m_vc = NULL;}if (m_mem != NULL){delete m_mem;m_mem = NULL;}cout << "销毁电脑" << endl;}void work(){m_cpu->calculate();m_vc->display();m_mem->storage();}
private:CPU* m_cpu;VideoCard* m_vc;Memory* m_mem;
};
Intel零件:
class IntelCPU :public CPU
{
public:virtual void calculate(){cout << "Intel的CPU开始计算" << endl;}
};
class IntelVideoCard :public VideoCard
{
public:virtual void display(){cout << "Intel的显卡开始工作" << endl;}
};
class IntelMemory :public Memory
{
public:virtual void storage(){cout << "Intel的内存条开始存储" << endl;}
};
联想零件:
class LenovoCPU :public CPU
{
public:virtual void calculate(){cout << "Lenovo的CPU开始计算" << endl;}
};
class LenovoVideoCard :public VideoCard
{
public:virtual void display(){cout << "Lenovo的显卡开始工作" << endl;}
};
class LenovoMemory :public Memory
{
public:virtual void storage(){cout << "Lenovo的内存条开始存储" << endl;}
};
组转电脑:
void test()
{CPU* intelcpu = new IntelCPU;VideoCard* intelvc = new IntelVideoCard;Memory* intelmem = new IntelMemory;Computer* pc1 = new Computer(intelcpu, intelvc, intelmem);pc1->work();delete pc1;CPU* lcpu = new LenovoCPU;VideoCard* lvc = new LenovoVideoCard;Memory* lmem = new LenovoMemory;Computer* pc2 = new Computer(lcpu, lvc, lmem);pc2->work();delete pc2;
}