多态案例三-电脑组装

案例描述:

电脑主要组成部件为CPU(用于计算),显卡(用于显示),内存条(用于存储)

将每个零件封装出抽象基类,并且提供不同的厂商不同的零件,例如Intel厂商和Lenovo厂商

创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口

测试时组装三台不同的电脑进行工作

示例:

#include<iostream>
using namespace std;
#include<string>
//零件类
//抽象的CPU类
class CPU
{
public:
	virtual void Calculate() = 0;
};
//抽象的显卡类
class VideCard
{
public:
	virtual void Display() = 0;
};
//抽象的内存类
class Memory
{
public:
	virtual void Storage() = 0;
};
//Intel厂商
class IntelCPU:public CPU
{
public:
	virtual void Calculate()
	{
		 cout << "InterCPU开始计算了" << endl;
	}
};
class IntelVideCard :public VideCard
{
public:
	virtual void Display()
	{
		cout << "InterVideoCart显卡开始显示了" << endl;
	}
};
class IntelMemory :public Memory
{
public:
	virtual void Storage()
	{
		cout << "InterMenory内存条开始存储了" << endl;
	}
};
//Lenovo厂商
class LenovoCPU :public CPU
{
public:
	virtual void Calculate()
	{
		cout << "LenovoCPU开始计算了" << endl;
	}
};
class LenovoVideCard :public VideCard
{
public:
	virtual void Display()
	{
		cout << "LenovoVideoCart显卡开始显示了" << endl;
	}
};
class LenovoMemory :public Memory
{
public:
	virtual void Storage()
	{
		cout << "LenovoMenory内存条开始存储了" << endl;
	}
};
//电脑类
class Computer
{
public:
	Computer(CPU* cpu,VideCard* vc,Memory* mem)
	{
		m_cpu = cpu;
		m_vc = vc;
		m_mem = mem;
	}
	void work()
	{
		m_cpu->Calculate();
		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;
	VideCard* m_vc;
	Memory* m_mem;
};
void test01()
{
	Computer* computer1 =new Computer (new IntelCPU, new IntelVideCard, new IntelMemory);
	computer1->work();
	delete computer1;
	cout << "__________________________" << endl;
	Computer* computer2 = new Computer(new LenovoCPU, new LenovoVideCard, new LenovoMemory);
	computer2->work();
	delete computer2;
	cout << "__________________________" << endl;
	Computer* computer3 = new Computer(new LenovoCPU, new IntelVideCard, new LenovoMemory);
	computer3->work();
	delete computer3;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值