Decorator - shoonie/StudyingDesignPattern GitHub Wiki
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
- More flexibility than static inheritance.
- Avoids feature-laden classes high up in the hierarchy.
- A decorator and its component aren't identical.
- Lots of little objects.
- Interface conformance.
- Omitting the abstract Decorator class.
- Keeping Component classes lightweight.
- Changing the skin of an object versus changing its guts.
// good example of https://cppcodetips.wordpress.com/2016/10/31/decorator-pattern-explained-with-c-sample/
#include "stdafx.h"
#include <iostream>
class IiceCream
{
public:
virtual void Make() = 0;
virtual ~IiceCream() { }
};
class SimpleIceCream : public IiceCream
{
public:
virtual void Make()
{
std::cout << "\n milk + sugar + Ice cream Powder";
}
};
class IceCreamDecorator : public IiceCream
{
public:
IceCreamDecorator(IiceCream& decorator) :m_Decorator(decorator)
{
}
virtual void Make()
{
m_Decorator.Make();
}
private:
IiceCream & m_Decorator;
};
class WithFruits : public IceCreamDecorator
{
public:
WithFruits(IiceCream& decorator) :IceCreamDecorator(decorator)
{
}
virtual void Make()
{
IceCreamDecorator::Make();
std::cout << " + Fruits";
}
};
class WithNuts : public IceCreamDecorator
{
public:
WithNuts(IiceCream& decorator) :IceCreamDecorator(decorator)
{
}
virtual void Make()
{
IceCreamDecorator::Make();
std::cout << " + Nuts";
}
};
class WithWafers : public IceCreamDecorator
{
public:
WithWafers(IiceCream& decorator) :IceCreamDecorator(decorator)
{
}
virtual void Make()
{
IceCreamDecorator::Make();
std::cout << " + Wafers";
}
};
int _tmain(int argc, _TCHAR* argv[])
{
IiceCream* pIceCreamSimple = new SimpleIceCream();
pIceCreamSimple->Make();
IiceCream* pIceCreamFruits = new WithFruits(*pIceCreamSimple);
pIceCreamFruits->Make();
IiceCream* pIceCreamNuts = new WithNuts(*pIceCreamFruits);
pIceCreamNuts->Make();
IiceCream* pIceCreamWafers = new WithWafers(*pIceCreamNuts);
pIceCreamWafers->Make();
delete pIceCreamSimple;
delete pIceCreamFruits;
delete pIceCreamNuts;
delete pIceCreamWafers;
return 0;
}