码迷,mamicode.com
首页 > 其他好文 > 详细

Open closed principle

时间:2018-10-19 02:01:38      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:ace   display   clu   col   ret   return   string   space   mount   

#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;
}
技术分享图片

 

Open closed principle

标签:ace   display   clu   col   ret   return   string   space   mount   

原文地址:https://www.cnblogs.com/aelite/p/9813888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!