zoukankan      html  css  js  c++  java
  • 设计模式之依赖倒置原则讲解

    #include<iostream>
    using namespace std;
    class Book
    {
    public:
        void getContent()
        {
            cout << "从前有座山,山上有座庙,庙里有个小和尚,小和尚在听老和尚讲故事,从前有座山..." << endl;   
        }
    };
    class Mother
    {
    public:
        void Tell_Story(Book &s)
        {
            s.getContent();
        }
    };
    int main()
    {
        Mother a;
        Book s;
        a.Tell_Story(s);
    
    
    
        while (1);
        return 0;
    }

    上面的例子是一位妈妈再给孩子讲故事,但随着孩子年纪的增大,比如:

    class NewsPaper
    {
    public:
        void getContent()
        {
            cout << "欢迎观看今日的新闻联播,据报道,今日某地区。。。" << endl;
        }
    };

    如果想让这位妈妈讲讲报纸,这位妈妈却办不到,除非他在自己的代码里面再加入新的函数,或者把自己原来的函数改变。

    那么有什么办法呢?

    #include<iostream>
    using namespace std;
    class IRead
    {
    public:
        virtual void getContent() = 0;
    };
    class Book:public IRead
    {
    public:
        void getContent()
        {
            cout << "从前有座山,山上有座庙,庙里有个小和尚,小和尚在听老和尚讲故事,从前有座山..." << endl;   
        }
    };
    class NewsPaper:public IRead
    {
    public:
        void getContent()
        {
            cout << "欢迎观看今日的新闻联播,据报道,今日某地区。。。" << endl;
        }
    };
    class Mother
    {
    public:
        void Tell_Story(IRead &s)
        {
            s.getContent();
        }
    };
    int main()
    {
        Mother a;
        Book s;
        NewsPaper p;
        a.Tell_Story(s);
        a.Tell_Story(p);
    
        while (1);
        return 0;
    }

     

  • 相关阅读:
    匈牙利算法(Kuhn-Munkres)算法
    城城城城
    Windows平台将远程服务器的目录挂载为本地磁盘
    怎么看自己电脑的内存多少赫兹
    sqlserver isnull函数
    带参数的存储过程
    EFCore学习记录笔记
    js保留两位小数方法总结
    C#中 ??、 ?、 ?: 、?.、?[ ] 问号
    C#枚举转化示例大全,数字或字符串转枚举
  • 原文地址:https://www.cnblogs.com/SunShine-gzw/p/13255383.html
Copyright © 2011-2022 走看看