案例描述:
电脑主要组成部件为CPU (用于计算),显卡(用于显示),内存条(用于存储)
将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如IntelF商和Lenovo商创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作
#include <iostream> using namespace std; #include <string> //抽象CPU类 class CPU { public: virtual void caculate() = 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; } //提供工作的函数 void work() { m_cpu->caculate(); m_vc->display(); m_mem->storage(); } //提供电脑零件的析构函数 ~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; } } private: CPU * m_cpu; VideoCard* m_vc; Memory* m_mem; }; //Intel厂商CPU功能 class IntelCPU :public CPU { public: virtual void caculate () { cout << "Intel计算机开始计算" << endl; } }; //Intel厂商VideoCard功能 class IntelVideoCard :public VideoCard { public: virtual void display() { cout << "Intel计算机开始显示" << endl; } }; //Intel厂商Memory功能 class IntelMemory:public Memory { public: virtual void storage() { cout << "Intel计算机开存储" << endl; } }; //Lenovo厂商CPU功能 class LenovoCPU :public CPU { public: virtual void caculate() { cout << "Lenovo计算机开始计算" << endl; } }; //Lenovo厂商VideoCard功能 class LenovoVideoCard :public VideoCard { public: virtual void display() { cout << "Lenovo计算机开始显示" << endl; } }; //Lenovo厂商Memory功能 class LenovoMemory :public Memory { public: virtual void storage() { cout << "Lenovo计算机开存储" << endl; } }; void Test() { //第一台电脑零件 CPU* intelCpu = new IntelCPU; //父类指针指向子类对象,利用多态 VideoCard* intelCard = new IntelVideoCard; Memory* intelMem = new IntelMemory; //第一台电脑 cout << "第一台电脑开始工作:" << endl; Computer* computer1 = new Computer(intelCpu, intelCard, intelMem); computer1->work(); delete computer1; //第二台电脑组装 cout << "------------------" << endl; cout << "第二台电脑开始工作:" << endl; Computer* computer2 = new Computer(new LenovoCPU, new LenovoVideoCard, new LenovoMemory); computer2->work(); delete computer2; //第三台电脑组装 cout << "------------------" << endl; cout << "第三台电脑开始工作:" << endl; Computer* computer3 = new Computer(new LenovoCPU, new IntelVideoCard, new LenovoMemory); computer3->work(); delete computer3; } int main() { Test(); system("pause"); return 0; }资料代码参考 黑马程序员
如有侵权,请与本人联系