设计模式之依赖倒置原则讲解

#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;
}

设计模式之依赖倒置原则讲解

 设计模式之依赖倒置原则讲解

设计模式之依赖倒置原则讲解