samedi 24 janvier 2015

polymorphic behaviour through composition in c++ without multilevel inheritance

I would like to achieve the polymorphic behavior through composition , instead of multilevel inheritance.in below example code bluerectangle is derived from rectangle and bluecircle is derived from circle. so the problem is I might have same depth in inheritance hierarchy so the job is to reduce the hierarchy level using composition instead of multilevel inheritance .can we achieve the polymorphic behavior here with composition, if yes then what design needs to be followed here. currently I just started reading design pattern so it seems to be similar to bridge pattern , but not able to proceed further without having proper pointers.



#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;
}

Aucun commentaire:

Enregistrer un commentaire