C++ 面向抽象类编程-电脑组装案例

#include<iostream>

using namespace std;
//------------抽象层----------
//抽象的CPU类
class CPU {
public:
	virtual void caculate() = 0;
};

//抽象的显卡类
class Aard {
public:
	virtual void display() = 0;
};

//抽象内存类
class Memory {
public:
	virtual void storage() = 0;
};

//架构类面相抽象类
class Computer {
public:
	Computer(CPU*cpu, Aard*aard, Memory*memory) {
		this->cpu = cpu;
		this->aard = aard;
		this->memory = memory;
	}
	void work() {
		this->cpu->caculate();
		this->aard->display();
		this->memory->storage();
	}
	
private:
	CPU*cpu;
	Aard*aard;
	Memory*memory;
};
//------------------------------------

//--------------实现层----------------
//英特尔公司的CPU
class IntelCPU :public CPU {
public:
	virtual void caculate() {
		cout << "英特尔公司的CPU开始计算了!" << endl;
	}
};
//英特尔公司的Aard
class IntelAard :public Aard {
public:
	virtual void display() {
		cout << "英特尔公司的显卡开始显示了!" << endl;
	}
};
//英特尔公司的memory
class IntelMemory :public Memory {
public:
	virtual void storage() {
		cout << "英特尔公司的内存条开始存储了!" << endl;
	}
};
//金士顿的内存
class KingstonMem :public Memory {
public:
	virtual void storage() {
		cout << "金士顿公司的内存条开始存储了!" << endl;
	}
};
//NVIDIA的显卡
class NVIDIAaard :public Aard {
public:
	virtual void display() {
		cout << "NVIDIA公司的显卡开始显示了!" << endl;
	}
};

//--------------------------------------

//-----------业务层---------------------

int main(void)
{
	//1 组装一台Intel系列的电脑
	CPU*cp = new IntelCPU;
	Aard* aa = new IntelAard;
	Memory* me = new IntelMemory;

	Computer* de=new Computer(cp, aa, me);
	de->work();
	delete aa;
	delete me;
	delete de;

	cout << "----------------------" << endl;
	//2.组装一台CPU是Intel的,显卡是NVIDIA的,内存是Kingston的电脑
	Aard* Naard = new NVIDIAaard;
	Memory* KMemory = new KingstonMem;

	Computer* to = new Computer(cp, Naard, KMemory);
	to->work();
	delete cp;
	delete Naard;
	delete KMemory;
	delete to;
	
}
//--------------------------------------

程序运行结果如下图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43778462/article/details/95048419