Decorator - shoonie/StudyingDesignPattern GitHub Wiki

Intent

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Diagram

disgram

Consequences

  1. More flexibility than static inheritance.
  2. Avoids feature-laden classes high up in the hierarchy.
  3. A decorator and its component aren't identical.
  4. Lots of little objects.

Implementation

  1. Interface conformance.
  2. Omitting the abstract Decorator class.
  3. Keeping Component classes lightweight.
  4. Changing the skin of an object versus changing its guts.

Sample Code

// 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;
}
⚠️ **GitHub.com Fallback** ⚠️