//多态案例三-电脑组长

//多态案例三-电脑组长

//案例描述:
//电脑主要组成部件为CPU(用于计算),显卡(用于显示),内存条(用于存储)
//将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel产商
/和Lenovo厂商创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口测试时组装三台不同的电脑进行工作/

#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 storage() = 0;
};
//电脑类
class Computer
{
public:
Computer(CPU* cpu, VideoCard* vc, Memory* men)
{
m_cpu = cpu;
m_vc = vc;
m_men = men;
}

void wokr()
{
	//让零件运行起来
	m_cpu->calculate();

	m_vc->display();

	m_men->storage();

}
//提供析构函数 释放三个电脑零件
~Computer()
{
	//释放cpu零件
	if (m_cpu != NULL)
	{
		delete m_cpu;
		m_cpu = NULL;
	}
	//释放显卡零件
	if (m_vc != NULL)
	{
		delete m_vc;
		m_vc = NULL;
	}
	//释放内存零件
	if (m_men != NULL)
	{
		delete m_men;
		m_men = NULL;
	}
}

private:
CPU* m_cpu;//CPU的零件指针
VideoCard* m_vc;//显卡零件指针
Memory* m_men;//内存条零件指针
};

//Lenovo厂商
//intel厂商

class IntelCPU :public CPU
{
public:
	virtual void calculate()
	{
		cout << "Intel的CPU开始计算了" << endl;
	}
};
class IntelCPUVideoCard :public VideoCard
{
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 VideoCard
{
public:
	virtual void display()
	{
		cout << "Lenovo的显卡开始计算了" << endl;
	}
};
class LenovoMemory :public Memory
{
public:
	virtual void storage()
	{
		cout << "Lenovo的内存条开始计算了" << endl;
	}
};

void test01()
{
//第一台电脑零件
CPU * intelCpu = new IntelCPU;
VideoCard* intelCard = new IntelCPUVideoCard;
Memory* intelMen = new IntelMemory;

//创建第一台电脑
Computer* computer1 = new Computer(new IntelCPU, new IntelCPUVideoCard, new  IntelMemory);
computer1->wokr();
delete computer1;

//第二台电脑零件
intelCpu = new LenovoCPU;
 intelCard = new LenovoVideoCard;
intelMen = new  LenovoMemory;

//创建第二台电脑
Computer* computer2 = new Computer(new LenovoCPU, new LenovoVideoCard, new  LenovoMemory);
computer2->wokr();
delete computer2;

}

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

猜你喜欢

转载自blog.csdn.net/ADADQDQQ/article/details/108333159