#include<iostream>
using namespace std;
#if 0
C++有一种设计原则叫做依赖导致,也是基于多态的。
定义:高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该依赖细节;
细节应该依赖抽象。
#endif
//这个I是interface的意思。
class IReader
{
public:
virtual string getContents()=0;
};
class Book:public IReader
{
public:
virtual string getContents()
{
return "从前有座山,山里有座庙,庙里有个小和尚,要听老和尚讲故事";
}
};
class NewsPaper:public IReader
{
public:
virtual string getContents()
{
return "hello world";
}
};
//这个叫做高层业务逻辑,但是设计的时候基本不要动高层业务逻辑。
//然后那两个就叫底层逻辑,如果你每加一个底层就动用一次高层逻辑
//比如这里你加了一个NewsPaper,你如果按照以前的就又要在mother下面加一个
//void tellStory(NewsPaper &b),这样太麻烦了。
//是不是有点不太好。怎么办呢,那我们在中间加一个抽象层。以后只需要改底层就可以了。抽象层和底层都不需要动就能完成我们新的功能。
//所以我们这里Mother叫顶层业务逻辑,不需要动。中间层就是这个接口层,叫做抽象层。然后NewsPaper这种就是底层。然后这个mother就依赖于IReader,然后底层也依赖于IReader。所以你在结合上面的那句高层模块不应该依赖于底层模块,两者都应该依赖抽象。
class Mother
{
public:
void tellStory(IReader *b)
{
cout<<b->getContents()<<endl;
}
};
int main()
{
Book b;
NewsPaper c;
Mother m;
cout<<"mother start to tell stroy"<<endl;
m.tellStory(&b);
m.tellStory(&c);
cin.get();
return 0;
}
C++学习之25
最新推荐文章于 2023-05-04 22:28:58 发布