c++ - 通过 C++ 中的组合实现多态行为,无需多级继承

标签 c++ design-patterns polymorphism virtual composition

我想通过组合来实现多态行为,而不是多级继承。在下面的示例代码中,bluerectangle源自矩形,bluecircle源自circle。所以问题是我的继承层次结构可能具有相同的深度,因此工作是使用组合而不是多级继承来减少层次结构级别。我们可以通过组合实现这里的多态行为吗?如果是,那么这里需要遵循什么设计。目前我刚刚开始阅读设计模式,因此它似乎与桥接模式类似,但如果没有正确的指针,则无法进一步进行。

 #include<iostream>
    using namespace std;
    class shape
    {
    public:
    virtual void draw()=0;
    virtual ~shape(){}
    };

    class rectangle: public shape
    {
    public:
    void draw()
    {
    cout<<"draw rectangle"<<endl;
    }
    }; 
    class bluerectangle : public rectangle
    {
    public:
    void draw()
    {
    cout<<"draw bluerectangle"<<endl;
    }
    };
    class circle: public shape
    {
    public:
    void draw()
    {
    cout<<"draw circle"<<endl;
    }

    }; 

    class bluecircle : public circle
    {
    public:
    void draw()
    {
    cout<<"draw bluecircle"<<endl;
    }
    };

    int main()
    {
    shape *obj=new circle;
    obj->draw();
    obj=new rectangle;
    obj->draw();
    obj=new bluerectangle;
    obj->draw();
    obj=new bluecircle;
    obj->draw();
    delete obj;
    return 1;
    }

最佳答案

根据您在评论中的回答,这是一个经典的装饰器模式。

Decorator applied to OP's problem

要获得红色矩形,请将其包裹起来:

Shape *obj=new RedDecorator(new Rectangle);
obj->draw();

装饰器的 draw() 调用矩形的 draw() 并增强它(装饰它)。

关于c++ - 通过 C++ 中的组合实现多态行为,无需多级继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28123773/

相关文章:

模板化单例的 C++ 工厂

c++ - using-declaration 无法正常工作

c++ - 为什么要在运行时处理虚函数?

c++ - 接受一个元组并返回另一个元组的函数

c++ - 动态 SQL 与静态 SQL

c++ - 游戏模式中更新方法的参数

python - 数据解析和特征工程管道的设计模式

c++ - 链接静态 C++ 库时 Objective-C 中的损坏符号表

c++ - 是否需要删除未实例化为变量的指针?

scala - 函数式面向对象语言的类型系统