多型 案例三 (電腦組裝)

新鮮感~發表於2020-12-17
#include<iostream>
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* mem)
	{
		m_cpu = cpu;
		m_vc = vc;
		m_mem = mem;

	}
		//提供工作函式
		void work()
		{
			m_cpu->calculate();
			m_vc->display();
			m_mem->storage();
		}
	

		//提供解構函式 釋放3個電腦零件
		~Computer()
		{
			//釋放CPU
			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;//記憶體條

};



//具體廠商
class IntelCPU : public CPU
{
public :
	virtual void calculate()
	{
		cout << "Intel的CPU開始計算了!" << endl;
	}
};


class IntelVideoCard : 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 IntelVideoCard;
	Memory* intelMen = new IntelMemory;



	


	//建立第一臺電腦

	Computer* computer1 = new Computer(intelCpu, intelCard, intelMen);
	computer1->work();
	delete computer1;




	//組裝第二臺電腦

	cout << "第二臺電腦開始工作" << endl;

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

}

















int main()
{
	test01();








	return 0;




}

相關文章