Open closed principle
阿新 • • 發佈:2018-10-19
open ont The mage interface left other virt dso
#include <iostream> using namespace std; class Book { public: string getContents() { return "Long time ago,There is a temple in the mountain"; } }; class Paper { public: string getContents() { return "I am handsome"; } }; class Mother { public:void tellstory(Book* b) { cout << b->getContents() << endl; } void tellstory(Paper* p) { cout << p->getContents() << endl; } }; int main(int argc, char *argv[]) { Book b; Mother m; Paper p; m.tellstory(&b); m.tellstory(&p); return 0; }
#include <iostream> using namespace std; class iReader { public: virtual string getContents() = 0;//only provide a interface }; class Book : public iReader { public: string getContents() { return "Long time ago,There is a temple in the mountain"; } }; class Paper : public iReader { public: string getContents() { return "I am handsome"; } }; class Mother { public: void tellstory(iReader * r) { cout << r->getContents() << endl; } }; int main(int argc, char *argv[]) { Book b; Mother m; Paper p; m.tellstory(&b); m.tellstory(&p); return 0; }
![技術分享圖片](http://image.bubuko.com/info/201810/20181019015024534332.png)
Open closed principle