飞道的博客

C++基于多态实现依赖颠倒原则附源码

459人阅读  评论(0)

依赖颠倒原则

关于多态的实现原理以及实例见前几天更新的C++多态一文:
C++多态

使用依赖颠倒原则之后,虽然代码实现比原来更加复杂了,但是实现了高层业务逻辑层与底层模块之间的解耦合,更改或者更换底层模块不在需要改动高层模块的代码就可以实现,整个系统的更加的稳定。

传统的过程式设计倾向于使用高层的模块依赖低层次的模块,抽象层依赖于具体层

没有使用依赖颠倒之前,上层业务逻辑依赖底层业务逻辑

依赖颠倒原则
使用了依赖颠倒之后,上层业务逻辑和底层模块都依赖于抽象层,代码复杂了,但是系统易于维护了

依赖颠倒的实现也是基于多态的基础之上,,具体的Cpp代码实现如下:

#include <iostream>
using namespace std;

// 让computer框架和具体的厂商 进行解耦合
// 1. 定义虚类,主要目的是为了规定后期子类的行为
class HardDisk
{
   
public:
    virtual void work(void) = 0;
};

class Memory
{
   
public:
    virtual void work(void) = 0;
};

class Cpu
{
   
public:
    virtual void work(void) = 0;
};

class Computer
{
   
public:
    Computer(HardDisk *hardDisk, Memory *memory, Cpu *cpu)
    {
   
        m_hardDisk = hardDisk;
        m_memory = memory;
        m_cpu = cpu;
    }
    void work()
    {
   
        m_hardDisk->work();
        m_memory->work();
        m_cpu->work();
    }

private:
    HardDisk *m_hardDisk;
    Memory *m_memory;
    Cpu *m_cpu;
};

class InterCpu : public Cpu
{
   
public:
    void work(void)
    {
   
        cout << "inter cpu work status ok." << endl;
    }
};

class XSDisk : public HardDisk
{
   
public:
    void work(void)
    {
   
        cout << "xs data work status ok." << endl;
    }

};

class KingStonMemory : public Memory
{
   
public:
    void work(void)
    {
   
        cout << "KingSton memory status is ok." << endl;
    }
};

int main(int argc, char const *argv[])
{
   
    // 基于多态实现依赖颠倒
    HardDisk *hardDisk = NULL;
    Memory *memory = NULL;
    Cpu *cpu = NULL;

    hardDisk = new XSDisk;
    memory = new KingStonMemory;
    cpu = new InterCpu;

    Computer *myComputer = new Computer(hardDisk, memory, cpu);
    myComputer->work();

    delete myComputer;
    delete cpu;
    delete memory;
    delete hardDisk;

    cout << "hello world." << endl;
    return 0;
}

执行结果:

xs data work status ok.
KingSton memory status is ok.
inter cpu work status ok.
hello world.

转载:https://blog.csdn.net/andrewgithub/article/details/108954306
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场