案例:计算机组装
描述:计算机主要部件为CPU、显卡、内存条,分别用于计算、显示、存储。将每个零件封装出抽象基类,并提供两个厂商(Intel和Lenovo),创建计算机类提供工作的函数,并调用零件工作的接口。
#include<iostream>
#include<string>
using namespace std;
//抽象CPU类
class CPU
{
public:
//抽象计算函数
virtual void calculate() = 0;
};
//抽象显卡类
class Videocare
{
public:
//抽象显示函数
virtual void display() = 0;
};
//抽象内存条类
class Memory
{
public:
//抽象存储函数
virtual void storage() = 0;
};
//计算机类
class Computer
{
public:
Computer(CPU *cpu, Videocare *vc, Memory *mem)
{
m_cpu = cpu;
m_vc = vc;
m_mem = mem;
}
//提供工作函数
void work()
{
//调用接口,零件工作
m_cpu->calculate();
m_vc->display();
m_mem->storage();
}
//提供析构函数 释放3个计算机零件
~Computer()
{
if (m_cpu != 0)
{
//释放CPU零件
delete m_cpu;
m_cpu = NULL;
//释放显卡零件
delete m_vc;
m_vc = NULL;
//释放内存条零件
delete m_mem;
m_mem = NULL;
}
}
private:
CPU *m_cpu; //CPU零件指针
Videocare *m_vc; //显卡零件指针
Memory *m_mem; //内存条零件指针
};
//具体厂商
//Intel
class IntelCPU :public CPU
{
public:
virtual void calculate()
{
cout << "Intel的CPU开始计算" << endl;
}
};
class IntelVideoCard :public Videocare
{
public:
virtual void display()
{
cout << "Intel的显卡开始显示" << endl;
}
};
class IntelMemory :public Memory
{
public:
virtual void storage()
{
cout << "Intel的内存条开始存储" << endl;
}
};
//Lenovo
class LenovoCPU :public CPU
{
public:
virtual void calculate()
{
cout << "Lenovo的CPU开始计算" << endl;
}
};
class LenovoVideoCard :public Videocare
{
public:
virtual void display()
{
cout << "Lenovo的显卡开始显示" << endl;
}
};
class LenovoMemory :public Memory
{
public:
virtual void storage()
{
cout << "Lenovo的内存条开始存储" << endl;
}
};
void test01()
{
//第一台计算机零件
CPU *intelCPU = new IntelCPU;
Videocare *intelCard = new IntelVideoCard;
Memory * interMemory = new IntelMemory;
//创建第一台计算机
cout << "第一台计算机开始工作" << endl;
Computer *computer1 = new Computer(intelCPU, intelCard, interMemory);
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()
{
test01();
system("pause");
return 0;
}
运行结果如下: