Open closed principle

Posted aelite

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Open closed principle相关的知识,希望对你有一定的参考价值。

#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的主要内容,如果未能解决你的问题,请参考以下文章

开闭原则 Open Closed Principle

Open closed principle

如何在SOLID中从条件语句转换为OCP(Open Closed Principle)?

设计原则之-开闭原则(Open Close Principle, OCP)

开放封闭原则(Open Closed Principle)

“开-闭”原则 (Open-Closed principle, OCP)