C++两个原则

来源:互联网 发布:vb进度条控件使用 编辑:程序博客网 时间:2024/06/05 18:57
#include <iostream>
using namespace std;
/*2.抽象层业务逻辑*/
class IReader {// InterfaceReader   
 public:
virtual string getContent() = 0;
};  

/*3.底层业务逻辑*/ 
   //接口  细节 
class Book :public IReader{
public:
string getContent(){
 return "Book的内容";
}
};
//接口  细节 
class NewsPaper :public IReader{
public:
string getContent(){
 return "NewsPaper的内容";
}
};
//接口  细节 
class ElectricBook:public IReader{
public:
string getContent(){
return"ElectricBook的内容";
}
}; 
/*
大项目,架构动,则是重构,大的责任 
1.高层业务逻辑 
*/

class Mother{
 public:
  /*
  1.C++原则1:开闭原则:
 闭:高层业务的接口要高度抽象,不要试图修改。 
 开:如果有新的功能增加的话,通过增加类来实现 。
C++原则2:依赖倒置原则:
高层和底层依赖于其抽象,细节应依赖于抽象    
*/ 

void tellStroy(IReader *i){
cout<<i->getContent()<<endl;
}
/*
1.高层:每次新读一种,都要修改高层业务的内容 
void tellStroy(Book *i){
cout<<i->getContent()<<endl;
}
void tellStroy(NewsPaper *i){
cout<<i->getContent()<<endl;
}
*/
};


int main(){
    Mother m;
    Book b; // Book *b = new Book;
    cout<<"Mother start to tell 书:"<<endl;
m.tellStroy(&b);
    NewsPaper n;
cout<<"Mother start to tell 报纸:"<<endl;
m.tellStroy(&n);//m.tellStroy(b);
ElectricBook e ;
cout<<"Mother start to tell 电子书:"<<endl;
m.tellStroy(&e);//m.tellStroy(b);
   //delete b;
return 0;
}
原创粉丝点击