Decorator Design Pattern
This is one of structural design pattern.
The decorator pattern is a design pattern that extends the functionality of individual objects by wrapping them with one or more decorator classes. These decorators can modify existing members and add new methods and properties at run-time.
#include<iostream>
using namespace std;
class Product
{
public:
virtual int getPrice()=0;
};
class Item : public Product
{
int price;
string name;
public:
Item(string str, int value)
{
name = str;
price = value;
}
int getPrice()
{
return price;
}
};
class priceDecorator : public Product
{
protected:
Product *prod;
public:
};
class GST : public priceDecorator
{
int GSTSlab;
public:
GST(Product *p)
{
prod = p;
GSTSlab = 28;
}
int getPrice()
{
int price = prod->getPrice();
return price+price*GSTSlab/100;
}
};
class Discount : public priceDecorator
{
int discount;
public:
Discount(Product *p)
{
prod = p;
discount = 10;
}
int getPrice()
{
int price = prod->getPrice();
return price-price*discount/100;
}
};
int main()
{
Product *prod = new Discount(new GST(new Item("Pen", 100)));
cout<<"Total price of product is : "<<prod->getPrice()<<endl;
return 0;
}
The decorator pattern is a design pattern that extends the functionality of individual objects by wrapping them with one or more decorator classes. These decorators can modify existing members and add new methods and properties at run-time.
#include<iostream>
using namespace std;
class Product
{
public:
virtual int getPrice()=0;
};
class Item : public Product
{
int price;
string name;
public:
Item(string str, int value)
{
name = str;
price = value;
}
int getPrice()
{
return price;
}
};
class priceDecorator : public Product
{
protected:
Product *prod;
public:
};
class GST : public priceDecorator
{
int GSTSlab;
public:
GST(Product *p)
{
prod = p;
GSTSlab = 28;
}
int getPrice()
{
int price = prod->getPrice();
return price+price*GSTSlab/100;
}
};
class Discount : public priceDecorator
{
int discount;
public:
Discount(Product *p)
{
prod = p;
discount = 10;
}
int getPrice()
{
int price = prod->getPrice();
return price-price*discount/100;
}
};
int main()
{
Product *prod = new Discount(new GST(new Item("Pen", 100)));
cout<<"Total price of product is : "<<prod->getPrice()<<endl;
return 0;
}

Comments
Post a Comment