C++之依赖倒置原则
1. 依赖于具体抽象(接口),不依赖于具体的实现,也就是针对接口编程。
2. 实现高层业务和实现层、实现层和实现层之间的解耦合;
实例:
电脑框架和电脑内部的配件产品(或提供配件产品的厂商)实现解耦合
电脑框架(Computer)由硬盘(HardDisk),内存(Memory)和CPU组成,,,选择厂商分别为:
硬盘(XSDisk),内存(JSDMemory)和CPU(InterCPU)。
#include <iostream>
using namespace std;
class HandDisk
{
public:virtual void work() = 0; //抽象层
};
class Memory
{
public:virtual void work() = 0; //抽象层
};
class CPU
{
public:virtual void work() = 0; //抽象层
};class Computer
{
public:Computer(HandDisk *handdisk, Memory *memory, CPU *cpu){this->handdisk = handdisk; this->memory = memory; this->cpu = cpu;}void work() //电脑工作,也就是内存+硬盘+cpu协同工作 //高层业务逻辑向抽象层靠拢{handdisk->work(); memory->work(); cpu->work();}
private:HandDisk *handdisk;Memory *memory;CPU *cpu;
};//厂商、产品
class XSDisk :public HandDisk //实现虚函数重写 //实现层向中间抽象层靠拢,所以都是work()函数
{
public:void work(){ cout << "西数硬盘" << endl; }
};
class JSDMemory :public Memory //实现层向中间抽象层靠拢,所以都是work()函数
{
public:void work(){ cout << "JSD内存" << endl; }
};
class InterCPU :public CPU //实现层向中间抽象层靠拢,所以都是work()函数
{
public:void work(){ cout << "Interl的CPU" << endl; }
};void main()
{HandDisk *handdisk = NULL;Memory *memory = NULL;CPU *cpu = NULL;handdisk = new XSDisk;memory = new JSDMemory;cpu = new InterCPU;Computer *myComputer = new Computer(handdisk, memory, cpu);myComputer->work();delete myComputer;delete cpu;delete memory;delete handdisk;cout << "Hello" << endl;system("pause");return ;
}
分析:
1. 先确定框架,并确定抽象层
2. 高层业务逻辑向抽象层靠拢
3. 实现层向中间抽象层靠拢
4. 电脑工作,也就是内存+硬盘+cpu协同工作