案例:小明打算买两台组装电脑,假设电脑零部件包括CPU、GPU和内存组成。
一台电脑使用intel的CPU、GPU和内存条
一台电脑使用Huawei的CPU、GPU和Intel的内存条
分析:使用多态进行实现
将CPU、GPU和内存条定义为抽象类,内部分别定义其对应功能的纯虚函数
Intel的CPU继承CPU,并实现其内部的纯虚函数(calculate)
Intel的GPU继承GPU,并实现其内部的纯虚函数(display)
Intel的MEMORY继承MEMORY,并实现其内部的纯虚函数(memory)
同样华为也一样继承CPU、GPU和MEMORY并实现对应的纯虚函数
封装一个Computer类,包含CPU、GPU和MEMORY,其成员属性为CPU、GPU和MEMORY的指针
内部有个work方法,用于调用CPU、GPU和MEMORY对应的方法
最后小明通过Computer类进行组装自己的电脑,并运行
#include<iostream>
class CPU
{
public:
virtual void calculate() = 0;
};
class GPU
{
public:
virtual void display() = 0;
};
class MEMORY
{
public:
virtual void memory() = 0;
};
class Computer
{
public:
Computer(CPU *cpu,GPU *gpu,MEMORY *memory)
{
m_cpu = cpu;
m_gpu = gpu;
m_memory = memory;
}
void work()
{
m_cpu->calculate();
m_gpu->display();
m_memory->memory();
}
~Computer()
{
if (m_cpu != NULL)
{
delete m_cpu;
m_cpu = NULL;
}
if (m_gpu != NULL)
{
delete m_gpu;
m_gpu = NULL;
}
if (m_memory != NULL)
{
delete m_memory;
m_memory = NULL;
}
}
private:
CPU *m_cpu;
GPU *m_gpu;
MEMORY *m_memory;
};
class IntelCPU :public CPU
{
public:
virtual void calculate()
{
std::cout << "IntelCPU is calculate..." << std::endl;
}
};
class IntelGPU :public GPU
{
public:
virtual void display()
{
std::cout << "IntelGPU is display..." << std::endl;
}
};
class IntelMEMORY :public MEMORY
{
public:
virtual void memory()
{
std::cout << "IntelMEMORY is memory..." << std::endl;
}
};
class HuaweiCPU :public CPU
{
public:
virtual void calculate()
{
std::cout << "HuaweiCPU is calculate..." << std::endl;
}
};
class HuaweiGPU :public GPU
{
public:
virtual void display()
{
std::cout << "HuaweiGPU is display..." << std::endl;
}
};
class HuaweiMEMORY :public MEMORY
{
public:
virtual void memory()
{
std::cout << "HuaweiMEMORY is memory..." << std::endl;
}
};
int main(int argc,char **argv)
{
CPU *my_CPU = new IntelCPU;
GPU *my_GPU = new IntelGPU;
MEMORY *my_memory = new IntelMEMORY;
Computer *my_computer = new Computer(my_CPU, my_GPU, my_memory);
my_computer->work();
delete my_computer;
Computer* my_computer_2 = new Computer(new HuaweiCPU,new HuaweiGPU,new IntelMEMORY);
my_computer_2->work();
return 0;
}
运行效果: