4.7.6 多态案例三—电脑组装

#include
#include
using namespace std;

//抽象出不同的零件
//抽象CPU类
class CPU
{
public:
	//抽象出计算函数
	virtual void calculate() = 0;

};

//抽象显卡类
class VideoCard
{
public:
	//抽象出显示函数
	virtual void display() = 0;

};

//抽象内存条类
class Memory
{
public:
	//抽象出存储函数
	virtual void stoarge() = 0;

};


//电脑类
class Computer
{
public:
	Computer(CPU * cpu, VideoCard * vc, Memory *mem)
	{
		m_cpu = cpu;
		m_vc = vc;
		m_mem = mem;
	}

	//提供工作的函数
	void  work()
	{
		//让零件工作起来,调用接口
		m_cpu->calculate();
		m_vc->display();
		m_mem->stoarge();
	}

	//提供析构函数,释放3个电脑零件 
	~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;  //CPU的零件指针
	VideoCard * m_vc;  //显卡零件指针
	Memory *m_mem;  //内存条零件指针

};


//具体厂商
//Inter厂商
class  InterCPU : public CPU
{
	virtual void calculate()
	{
		cout << " Inter的CPU开始计算了!" << endl;
	}
};

class  InterVideoCard : public VideoCard
{
	virtual void display()
	{
		cout << " Inter的显卡开始显示了!" << endl;
	}
};

class  InterMemory : public Memory
{
	virtual void stoarge()
	{
		cout << " Inter的内存条开始存储了!" << endl;
	}
};

//Lenovo厂商
class  LenovoCPU : public CPU
{
	virtual void calculate()
	{
		cout << " Lenovo的CPU开始计算了!" << endl;
	}
};

class  LenovoVideoCard : public VideoCard
{
	virtual void display()
	{
		cout << " Lenovo的显卡开始显示了!" << endl;
	}
};

class  LenovoMemory : public Memory
{
	virtual void stoarge()
	{
		cout << " Lenovo的内存条开始存储了!" << endl;
	}
};

void test01()
{
	cout << "第一台电脑开始工作:" << endl;
	//第一台电脑零件
	CPU *intelCpu = new InterCPU;   //父类指针指向子类对象
	VideoCard * interCard = new InterVideoCard;
	Memory *  interMem = new InterMemory;

	//创建第一台电脑
	Computer * computer1 = new Computer(intelCpu, interCard, interMem);
	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 InterVideoCard, new LenovoMemory);
	computer3->work();
	delete computer3;

}


int main()
{
	test01(); 
	return 0;
}

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