4.7.6 多态案例3--电脑组装

文章目录

    • 案例描述
    • 示例

案例描述

电脑的组成:CPU,显卡,内存条
将每个零件封装成抽象基类,并且提供不同的厂商生产不同的零件,创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作

示例

#include 
#include 
#include 
#include 

using namespace std;

class CPU
{
public:
	//抽象计算函数
	virtual void caculator() = 0;
};


class GTX
{
public:
	//抽象显示函数
	virtual void display() = 0;
};

class Memory
{
public:
	//抽象存储函数
	virtual void storage() = 0;
};

class Computer
{
public:
	Computer(CPU *cpu, GTX *vc, Memory *mem)
	{
		m_cpu = cpu;
		m_vc = vc;
		m_mem = mem;

	}
	~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;
		}
	}
	void work()
	{
		m_cpu->caculator();
		m_vc->display();
		m_mem->storage();

	}

private:
	CPU *m_cpu;
	GTX *m_vc;
	Memory *m_mem;
};

class IntelCPU :public CPU
{
public:
	virtual void caculator()
	{
		cout << "Intel计算" << endl;
	}
};

class IntelGTX :public GTX
{
public:
	virtual void display()
	{
		cout << "Intel显示" << endl;
	}
};

class IntelMemory :public Memory
{
public:
	virtual void storage()
	{
		cout << "Intel内存" << endl;
	}
};

class LenovoCPU :public CPU
{
public:
	virtual void caculator()
	{
		cout << "Lenovo计算" << endl;
	}
};

class LenovoGTX :public GTX
{
public:
	virtual void display()
	{
		cout << "Lenovo显示" << endl;
	}
};

class LenovoMemory :public Memory
{
public:
	virtual void storage()
	{
		cout << "Lenovo内存" << endl;
	}
};


void test01()
{

	CPU * intelcpu = new IntelCPU;
	GTX * intelgtx = new IntelGTX;
	Memory * intelmem = new IntelMemory;

	//创建电脑
	Computer * computer1 = new Computer(intelcpu, intelgtx, intelmem);
	computer1->work();
	delete computer1;

	Computer * computer2 = new Computer(new LenovoCPU, new LenovoGTX, new LenovoMemory);
	computer2->work();
	delete computer2;


}
int main()
{
	test01();

	system("pause");
	return 0;
}

你可能感兴趣的:(C++学习记录,c++)