Decorator
A decorator implements the same interface as the object it wraps and adds behaviour before or after forwarding. You stack decorators without changing the wrapped type or the caller's static type.
Detailed Explanation
You have a Store with get/put. You want logging, then retries, then metrics. Inheritance would produce LoggingRetryMetricsStore for every combination. Decorators produce MetricsStore(RetryStore(LoggingStore(real))). Each layer is a Store. The caller still holds unique_ptr<Store>.
The pattern is composition plus a common interface. The decorator owns (or references) an inner Store and implements every method, even the ones it does not change. Forgetting to forward a new method on Store is the maintenance cost. Keep the interface small.
C++ ownership: the decorator usually unique_ptr<Store> the inner object so the stack of wrappers is one tree. A non-owning pointer is possible if someone else owns the core; then every decorator must not outlive it.
IO streams are the textbook C++ decorator: istream plus gzip_istream plus buffered_istream (in libraries that provide them). std::istream itself is a virtual interface; wrapping it is the pattern.
Decorator versus inheritance: a subclass adds behaviour but fixes the base at compile time and explodes combinations. Versus adapter: the interface stays the same. Versus strategy: strategy swaps the algorithm inside; decorator wraps the whole object.
A lambda you pass to sort is not a decorator. A function wrapper that logs then calls another function is.
Do not decorate in a hot inner loop if the extra virtual call matters; bake the behaviour into one type or a template policy. Decorators shine at boundaries (I/O, storage, RPC).
Code Examples
#include <iostream>
#include <memory>
#include <string>
#include <utility>
struct Store {
virtual ~Store() = default;
virtual void put(const std::string& key, std::string value) = 0;
};
struct MemoryStore : Store {
void put(const std::string&, std::string) override {}
};
class LoggingStore : public Store {
std::unique_ptr<Store> inner_;
public:
explicit LoggingStore(std::unique_ptr<Store> inner)
: inner_(std::move(inner)) {}
void put(const std::string& key, std::string value) override {
std::cout << "put " << key << '\n';
inner_->put(key, std::move(value));
}
};
int main() {
std::unique_ptr<Store> s =
std::make_unique<LoggingStore>(std::make_unique<MemoryStore>());
s->put("n", "1"); // prints: put n
}Common Gotchas
Incomplete forwarding
a new virtual on `Store` must be implemented in every decorator. A defaulted base method that is not virtual will skip decorators.
Decorator outlives a non-owned inner
dangling inner pointer. Own with `unique_ptr` unless the lifetime is obvious.
Order of wrapping is order of behaviour
`Log(Retry(x))` logs retries; `Retry(Log(x))` logs each attempt. Write it on purpose.
Too many virtual layers
stack templates (`template<class Inner> class Logging`) if the chain is compile-time and hot.