Saturday 16 June 2018

Decorator Design Pattern in C++ is Structural Design pattern

Do you need to extend the capabilities of your existing class instance at run-time? If the answer is yes then Decorator design pattern just provides the functionality you need.

When we have to change the capabilities of only a particular instance and not all the instances which will get created for a particular class, we have to use decorator design pattern.









#include
#include
using namespace std;



class Sandwitch
{

public:
        virtual void getDesc()=0;
        virtual double getCost()=0;
};

class WhiteBread:public Sandwitch
{
public:
        void getDesc(){cout<<"white bread"<        double getCost(){return 2.0;}

};
class ItalianBread:public Sandwitch
{
public:
        void getDesc(){cout<<"Italian bread"<        double getCost(){return 3.0;}

};
class Decorator:public Sandwitch
{
        Sandwitch *sw;
public:
       Decorator(Sandwitch *swa) {sw = swa;}
       virtual double getCost(){return sw->getCost();}
       virtual void getDesc()=0;

};
class CheeseDecorator:public Decorator
{
public:
        CheeseDecorator(Sandwitch *sw):Decorator(sw){};
        ~CheeseDecorator();

        void getDesc(){cout<<"cheese Decor:";}
        double getCost(){return (Decorator::getCost()+3.0);}

};
class VegDecorator:public Decorator
{
public:
        void getDesc(){cout<<"Veg Decor:";}
        double getCost(){return (Decorator::getCost()+2.0);}


};
int main()
{
        Sandwitch *sw = new CheeseDecorator(new ItalianBread());
        sw->getDesc();
        cout<getCost()<        delete sw;
}

OutPut:
cheese Decor:6

No comments:

Post a Comment