我想通过组合来实现多态行为,而不是多级继承。在下面的示例代码中,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;
}
最佳答案
根据您在评论中的回答,这是一个经典的装饰器模式。
要获得红色矩形,请将其包裹起来:
Shape *obj=new RedDecorator(new Rectangle);
obj->draw();
装饰器的 draw()
调用矩形的 draw()
并增强它(装饰它)。
关于c++ - 通过 C++ 中的组合实现多态行为,无需多级继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28123773/