Decorator (Design Pattern)

This structural pattern increases the functionality of a class.



Looks similar to a proxy, but it gets the object injected (aggregation).


#include <memory>
#include <iostream>

// Interface
class IHuman {
public:
    virtual void wakeUp() = 0;
};

// Normal class
class Human: public IHuman {
public:
    void wakeUp() {
        std::cout << "Eat breakfast." << std::endl;
    }
};

// Decorator
class Hero: public IHuman {
public:
    Hero(std::unique_ptr<IHuman> human) : m_Human(std::move(human)) {}

    void wakeUp() {
        m_Human->wakeUp();
        std::cout << "Save the world." << std::endl;
    }
private:
    std::unique_ptr<IHuman> m_Human;
};

int main() {
    std::unique_ptr<IHuman> human(new Human());
    std::unique_ptr<IHuman> hero(new Hero(std::move(human)));
    hero->wakeUp();
    // ...
    return 0;
}