Monday, February 24, 2020

Decorator Design Pattern


Decorator Design Pattern: -
                                      Adding some extra class ,function or object to an original class without changing its structure is called decorator pattern.”
It helps user to add some extra functionality in existing class, this type of design pattern comes under structural pattern because it behaves like a wrapper to existing class.
Decorator pattern is nothing but just decorating a class adding some extra element in that class.
Consider a demo example shown below.in this the original class is house consisting of walls, step, roof. Now we are decorating this house by adding window doors, doors by using their respective classes.















Code:-

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

    }
};
class NormalHouse:public House
{
public:
    void draw()
    {
        cout<<"Walls + Step + roof";
    }
};
class HouseDecorator:public House
{
public:
    HouseDecorator(House& dd):D_Decorator(dd)
    {

    }
    void draw()
    {
        D_Decorator.draw();
    }
private:
    House& D_Decorator;
};
class Door:public HouseDecorator
{
public:
    Door(House& dd):HouseDecorator(dd)
    {

    }
    void draw()
    {
        HouseDecorator::draw();
        cout<<"+Door";
    }
};
class Windowdoor:public HouseDecorator
{
public:
    Windowdoor(House& dd):HouseDecorator(dd)
    {

    }
    void draw()
    {
        //HouseDecorator::draw();
        cout<<"+Windowdoor"<<endl;
    }
};
int main()
{
    House* h=new NormalHouse();
    h->draw();
    House* d= new Door(*h);
    d->draw();
    House* w=new Windowdoor(*d);
    w->draw();
    return 0;

}

Result:-

         

2 comments:

Course Project: 3 Lane Car Game

Course Project Title:  3 lane car racing game Course Project Description:              The aim of our course project is to implement...