Bootstrap

C++的依赖颠倒原则

个人理解,即面向接口编程,即抽象基类做接口,使用这个的时候,不在乎具体怎么实现,使用抽象基类声明,接口部分由派生类具体实现。

读下面文章写的一个小例子

23个小案例带你吃透23种设计模式 | C++实现-云社区-华为云

#include <iostream>

using namespace std;

//电脑:屏幕,cpu,内存,显卡,硬盘,


class AbstractScreen {
public:
	virtual void information() = 0;
};

class AbstractCpu {
public:
	virtual void information() = 0;
};

class AbstractMemory {
public:
	virtual void information() = 0;
};

class AbstractGraphics {
public:
	virtual void information() = 0;
};

class AbstractHardDisk {
public:
	virtual void information() = 0;
};

class computer {
public:
	computer(AbstractScreen* _screen = nullptr, AbstractCpu* _cpu = nullptr, AbstractMemory* _memory = nullptr,
		AbstractGraphics* _graphics = nullptr, AbstractHardDisk* _disk = nullptr);

	void showInformation();

	void changeScreen(AbstractScreen* _screen) {
		screen = _screen;		//更换屏幕
	}

	
private:
	AbstractScreen* screen = nullptr;
	AbstractCpu* cpu = nullptr;
	AbstractMemory* memory = nullptr;
	AbstractGraphics* graphics = nullptr;
	AbstractHardDisk* hardDisk = nullptr;
};


class sanxingScreen : public AbstractScreen {
public:
	void information() {
		cout << "三星的屏幕" << endl;
	}
};

class LgScreen : public AbstractScreen {
public:
	void information() {
		cout << "罗技的屏幕" << endl;
	}
};

class coreCpu : public AbstractCpu {
public:
	void information() {
		cout << "酷睿的CPU" << endl;
	}
};

class Jinston : public AbstractMemory {
public:
	void information() {
		cout << "金士顿的内存条" << endl;
	}
};

class Asus : public AbstractGraphics {
public:
	void information() {
		cout << "华硕的显卡" << endl;
	}
};

class seagate :public AbstractHardDisk {
public:
	void information() {
		cout << "希捷的硬盘" << endl;
	}
};






int main()
{
	sanxingScreen myscreen;		//屏幕
	coreCpu myCpu;				//CPU
	Jinston mymemory;			//内存
	Asus myGraphics;			//显卡
	seagate myHardDisk;			//硬盘

	computer myComputer(&myscreen,&myCpu,&mymemory,&myGraphics,&myHardDisk);
	myComputer.showInformation();

	LgScreen myScreen2;			//第二块屏幕
	myComputer.changeScreen(&myScreen2);
	myComputer.showInformation();	//更换屏幕后的信息

	return 0;
}

computer::computer(AbstractScreen* _screen, AbstractCpu* _cpu, AbstractMemory* _memory, AbstractGraphics* _graphics, AbstractHardDisk* _disk)
	:screen(_screen),cpu(_cpu),memory(_memory),graphics(_graphics),hardDisk(_disk)
{

}

//展示电脑配置信息
void computer::showInformation()
{
	if (screen != nullptr)
	{
		screen->information();
	}

	if (cpu != nullptr)
	{
		cpu->information();
	}

	if (memory != nullptr)
	{
		memory->information();
	}

	if (graphics != nullptr)
	{
		graphics->information();
	}

	if (hardDisk != nullptr)
	{
		hardDisk->information();
	}

	cout << "\n" << "\n" << endl;
}

;