多态案例三-电脑组装

案例描述:

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

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

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

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

示例:

#include
using namespace std;
#include
//零件类
//抽象的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;
}

你可能感兴趣的:(电脑,c++,开发语言)