Skip to content

Decorator

Difficulty: Intermediate

Key concepts

  • decorator pattern
  • wrapping
  • forwarding
  • ownership of the wrapped object
  • order of decorators
  • What the Decorator pattern is for: adding a step to an object’s work, such as compressing, encrypting, counting, logging, or retrying, without changing its class and without a new class for every combination of steps.
  • How a decorator works: it has the same interface as the object it wraps, does its own step, and passes the call on.
  • Who owns what: here each decorator owns the object it wraps through std::unique_ptr, and the client owns the outermost one.
  • Why the order of decorators matters, and how to see the order in the code that builds the chain.
  • When a simpler tool, such as a wrapper function or one class with options, is enough.

A backup tool writes records to storage. Customers choose how:

  1. FR-1 Records can be compressed, so that they take less space.
  2. FR-2 Records can be encrypted, with a key the customer chooses.
  3. FR-3 The tool reports how many bytes the app wrote, for billing, whichever steps are chosen.
  4. FR-4 Every combination of the steps must work, including none, and what was written must be readable again.

More steps are expected: a checksum, and sending the bytes over the network instead of to a file.

To keep the example checkable by hand, compression here is run-length encoding, which replaces a run of equal bytes with a count and the byte, and encryption is XOR with a repeating key.

One class does the writing, and an options struct says which steps to run:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
// Which steps to run. The `= false` and the empty string are defaults, so
// `{}` means "no steps", and a caller can name only the ones they want:
// {.compress = true, .key = "k3y"} (designated initializers, C++20).
struct Options {
bool compress = false;
std::string key; // empty: do not encrypt
};
// Writes records to out: compressed if asked, then encrypted if asked.
// Every step lives inside this one class, in a fixed order, and the
// options choose which of them run.
class RecordWriter {
public:
RecordWriter(std::string& out, Options options);
void write(std::string_view bytes);
private:
std::string* out_; // borrowed: must outlive the writer
Options options_;
// The encryption step's state sits next to everything else's, in the
// same class. It carries on from one write to the next.
std::size_t position_ = 0; // the key byte for the next byte
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// One function runs every step: make a changeable copy of the bytes,
// compress it if asked, encrypt it if asked, then append it to the
// string. The order, compress then encrypt, is fixed by the order of the
// two `if`s. The loops are the same ones RleSink and XorSink use later.
void RecordWriter::write(std::string_view bytes) {
std::string data{bytes}; // a copy this function may change
if (options_.compress) {
// Run-length encoding: each run of up to 255 equal bytes becomes
// (count, byte). `i + run < data.size()` is tested first, so
// data[i + run] is never read past the end.
std::string encoded;
std::size_t i = 0;
while (i < data.size()) {
std::size_t run = 1;
while (i + run < data.size() && run < 255 && data[i + run] == data[i]) {
++run;
}
encoded += static_cast<char>(run); // the count, 1 to 255, as one byte
encoded += data[i];
i += run; // on to the next run
}
// Replace data with the compressed bytes. std::move hands over
// encoded's buffer instead of copying it; encoded is not used again.
data = std::move(encoded);
}
if (!options_.key.empty()) {
// XOR each byte with the next key byte, wrapping round the key.
// `char& byte` changes the characters of data in place.
for (char& byte : data) {
byte = static_cast<char>(byte ^ options_.key[position_]);
position_ = (position_ + 1) % options_.key.size();
}
}
out_->append(data);
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
std::string file; // stands in for the file; the writer borrows it
// The options are chosen by naming fields: compress, and encrypt
// with key. The order of the steps cannot be chosen.
before::RecordWriter writer{file, {.compress = true, .key = key}};
writer.write(record);
std::cout << "before: " << file.size() << " bytes written\n";

With two fixed steps that never change, this is fine, and easier to read than what follows. It starts to hurt as the requirements grow:

  • The order is fixed in the code. Compression always comes first, which is right for these two steps (the output below shows why). But a customer who needs a step between them, or a counting step at a particular point, needs a change to RecordWriter.
  • Every new step edits the same function. A checksum is a third if in write, with its own state in the class. Each step’s tests run through every other step’s code.
  • The steps cannot be reused. Sending the bytes over the network needs a second writer, and the compression and XOR loops would be copied into it.
  • FR-3 has no good home. Counting the bytes the app wrote is one more member and one more line in write, mixed in with the others.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_stream.cpp
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) records
// a failure, and prints both values, unless actual == expected. They come
// from the site's small test header, lld_test.hpp.
//
// The test writes "aaab" twice: once with no steps, which must store it
// unchanged, and once with both steps, which must read back as "aaab"
// after undoing the steps in reverse.
LLD_TEST(before_every_combination_goes_through_one_class) {
std::string plain;
// A temporary writer: created, used for one write, and destroyed at
// the end of the statement. `{}` gives the default Options: no steps.
before::RecordWriter{plain, {}}.write("aaab");
LLD_CHECK_EQ(plain, std::string{"aaab"});
std::string both;
before::RecordWriter{both, {.compress = true, .key = "k"}}.write("aaab");
LLD_CHECK_EQ(rle_decode(xor_with(both, "k")), std::string{"aaab"});
}
// There is no way to ask for "encrypt, then compress", or to add a
// step, without changing RecordWriter.

A second approach, a subclass for each combination (CompressedWriter, EncryptedWriter, CompressedEncryptedWriter), is worse: three steps already make eight classes, and the order is still fixed in each.

Data or job Belongs to Why
accept bytes every kind of destination and step the one operation the whole chain shares: the interface, Sink
append bytes to storage the destination the real work, at the end of the chain: MemorySink here
run-length encode the bytes the compression step its own class; it needs nothing from the others
the key, and where in the key we are the encryption step state that only XOR uses; it must carry on from one write to the next
the number of bytes seen the counting step state that only counting uses
the sink to pass the bytes on to every step shared by all steps: a base class for decorators
which steps, in which order the code that builds the chain a decision about configuration, made in one place

The last row is the important one. In the before-version, the order of the steps was a fact about RecordWriter. Here it becomes a fact about how the objects are put together.

Decorator adds behaviour to an object by wrapping it in another object that has the same interface. The wrapper does its own work before or after the call, and forwards the call to the object it wraps. Because the wrapper has the same interface, it can itself be wrapped, so steps stack up in any number and any order, and the client cannot tell a plain object from a decorated one.

Its participants:

  • The component: the interface the client uses. Here, Sink.
  • The concrete component: the object that does the real work. Here, MemorySink.
  • The decorator: a component that holds another component and forwards to it. Here, SinkDecorator.
  • The concrete decorators: each adds one step. Here, RleSink, XorSink, and CountingSink.
Every sink has write; a decorator is a sink that owns the next sink and passes bytes on to it
Text description of the diagram

A class diagram. Sink is an interface with one pure virtual function, write, which takes a string view of bytes. MemorySink implements Sink and holds a pointer to a string it appends to. SinkDecorator derives from Sink, is abstract, holds a unique pointer to a Sink called next_, and has a protected function next that returns it. RleSink, XorSink, and CountingSink derive from SinkDecorator, and each overrides write. XorSink also holds a key and a position in the key; CountingSink holds a count and has a count function. A filled-diamond composition line from SinkDecorator to Sink, with multiplicity 1, shows that every decorator owns exactly one sink, the next one in the chain.

Diagram source (Mermaid)
classDiagram
class Sink {
  <<interface>>
  +write(string_view bytes) void*
}
class MemorySink {
  -string* out_
  +write(string_view bytes) void
}
class SinkDecorator {
  <<abstract>>
  -unique_ptr~Sink~ next_
  #next() Sink&
}
class RleSink {
  +write(string_view bytes) void
}
class XorSink {
  -string key_
  -size_t position_
  +write(string_view bytes) void
}
class CountingSink {
  -size_t count_
  +write(string_view bytes) void
  +count() size_t
}
Sink <|.. MemorySink
Sink <|-- SinkDecorator
SinkDecorator <|-- RleSink
SinkDecorator <|-- XorSink
SinkDecorator <|-- CountingSink
SinkDecorator *-- "1" Sink : next_ (owns)

The loop in the diagram is what makes chains possible: a SinkDecorator is a Sink, and it owns a Sink, which may be another decorator.

At run time, main builds this chain:

The chain main builds: each object owns the next one, the bytes flow the same way, and the last sink borrows main's string
Text description of the diagram

A flowchart of the objects in main’s chain, from left to right. A unique pointer to Sink in main owns a CountingSink, which counts 24 bytes. The CountingSink owns an RleSink and writes 24 bytes to it. The RleSink compresses and writes 6 bytes to the XorSink it owns. The XorSink encrypts and writes 6 bytes to the MemorySink it owns. The MemorySink appends them to a string called file, which main owns and the MemorySink only borrows. Every arrow except that last one is both ownership and the direction the bytes travel.

Diagram source (Mermaid)
flowchart LR
C(["main: unique_ptr to Sink"]) -->|owns| K["CountingSink<br/>counts 24"]
K -->|owns, writes 24 bytes| R["RleSink<br/>compresses"]
R -->|owns, writes 6 bytes| X["XorSink<br/>encrypts"]
X -->|owns, writes 6 bytes| M["MemorySink"]
M -->|appends, borrows| F[("string file")]

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

sink.hpp
// Anything bytes can be written to: a file, a socket, or another sink.
// This is the one interface every piece of a chain shares. Code that holds
// a Sink& or a std::unique_ptr<Sink> calls write() without knowing whether
// it is talking to the real storage or to a decorator in front of it.
// Sink is abstract (write is pure virtual, `= 0`), so nobody can create a
// plain Sink, only an object of a class derived from it.
class Sink {
public:
// `= default` asks the compiler for the ordinary do-nothing
// constructor. It must be written out, because declaring the copy
// constructor below stops the compiler from providing one by itself.
Sink() = default;
// `= delete` forbids copying a sink, both as Sink b{a} and as b = a.
// Copying through a Sink& would copy only the Sink part (slicing), and
// copying a chain by accident would give two chains one string. With
// copying deleted and no move declared, sinks cannot be moved either;
// they live behind std::unique_ptr, and moving the pointer is enough.
Sink(const Sink&) = delete;
Sink& operator=(const Sink&) = delete;
// Virtual, because a chain is destroyed through a std::unique_ptr<Sink>
// that really points at, say, a CountingSink. A virtual destructor
// makes sure the derived class's destructor runs too.
virtual ~Sink() = default;
// Hands some bytes to the sink. std::string_view is a cheap, read-only
// view of characters that someone else owns: nothing is copied, and a
// sink must not keep the view after write returns. `= 0` makes this
// pure virtual: every concrete sink must say what writing means.
virtual void write(std::string_view bytes) = 0;
};
// The end of a chain: appends to a string the caller owns. It stands in
// for a file, so that the tests can read what was written. `final` means
// no class may derive from MemorySink.
class MemorySink final : public Sink {
public:
// Keeps the address of the caller's string; the string is not copied.
// `explicit` stops a std::string from turning into a MemorySink when
// nobody asked for one.
explicit MemorySink(std::string& out) : out_{&out} {}
// `override` asks the compiler to check that this really replaces
// Sink::write. append adds the bytes at the end of the string, so the
// bytes of several writes pile up in the order they were written.
void write(std::string_view bytes) override { out_->append(bytes); }
private:
std::string* out_; // borrowed: the string must outlive the sink
};
  • Sink is the interface: one function. Keeping it small matters, because every decorator must pass on every function of it.
  • Sink deletes copying, which makes every sink neither copyable nor movable. That blocks *a = *b through two Sink&s, which would copy only the base part (slicing), and it means a chain cannot be copied by accident. Not being movable costs nothing here, because sinks live behind std::unique_ptr, which moves the pointer.
  • Sink’s destructor is virtual. The chain is destroyed through std::unique_ptr<Sink>, which deletes a CountingSink or a MemorySink through a Sink*; without a virtual destructor, that would be undefined behaviour.
  • MemorySink borrows the string it appends to. It stands in for a file, so that the example and the tests can read what was written.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

decorators.hpp
// A sink that changes or watches the bytes, then passes them on to the
// sink it wraps. It owns the sink it wraps.
//
// The idea: a decorator IS a Sink (it derives from Sink), so it can stand
// wherever a Sink is expected, and it HAS a Sink (next_), which it writes
// to after doing its own step. Because the wrapped sink can itself be a
// decorator, decorators stack into a chain: counting, around compressing,
// around encrypting, around the real storage.
//
// SinkDecorator does not override write, so it is still abstract: only
// the concrete decorators below, which do, can be created.
class SinkDecorator : public Sink {
protected:
// `protected`: only classes derived from SinkDecorator can call these.
// The constructor takes the next sink by value as a std::unique_ptr,
// so the caller must hand over ownership with std::move (or pass a
// fresh std::make_unique). Throws std::invalid_argument if next is
// null, so a decorator always has somewhere to write.
explicit SinkDecorator(std::unique_ptr<Sink> next); // throws if null
// The sink to pass the bytes on to. Returns a reference, not the
// std::unique_ptr: derived classes may use the next sink, but cannot
// take it away or replace it. Safe to use without a null check,
// because the constructor refused a null pointer.
Sink& next() { return *next_; }
private:
// Sole owner of the next sink. When this decorator is destroyed, the
// unique_ptr destroys the next sink, which destroys the one after it,
// and so on: destroying the outermost sink tears down the whole chain.
std::unique_ptr<Sink> next_;
};

SinkDecorator holds what every decorator has in common: the next sink, owned through std::unique_ptr, and a check that there is one. SinkDecorator does not override write, so it is abstract already; its protected constructor states the intent that it is only a base.

The base class is a convenience, not a requirement. Each decorator could hold its own std::unique_ptr<Sink>. The base earns its place when the interface has more than one function: if Sink grew a flush, the base could forward it once for every decorator, and each decorator would override only the functions it changes.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

decorators.hpp
// Run-length encoding: each run of up to 255 equal bytes becomes two
// bytes, the length of the run and the byte. A stand-in for compression.
// "aaab" becomes 03 'a' 01 'b'. A run longer than 255 is split, because
// one byte cannot hold a larger count.
class RleSink final : public SinkDecorator {
public:
explicit RleSink(std::unique_ptr<Sink> next);
void write(std::string_view bytes) override;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

decorators.cpp
// Compresses this write's bytes into pairs (count, byte) and passes the
// pairs on. Each call is encoded on its own: a run split across two
// writes is stored as two runs. Never throws by itself.
void RleSink::write(std::string_view bytes) {
std::string encoded; // the pairs built so far
std::size_t i = 0; // where the current run starts
while (i < bytes.size()) {
// Measure the run that starts at i: keep going while there is a
// next byte, the count still fits in one byte (at most 255), and
// the next byte equals the first byte of the run. The order of
// the tests matters: `i + run < bytes.size()` comes first, so
// bytes[i + run] is never read past the end.
std::size_t run = 1;
while (i + run < bytes.size() && run < 255 && bytes[i + run] == bytes[i]) {
++run;
}
// Store the count as one byte, then the byte itself. The count is
// 1 to 255; static_cast<char> squeezes it into a char, and
// rle_decode reads it back as an unsigned char to get 1 to 255.
encoded += static_cast<char>(run);
encoded += bytes[i];
i += run; // jump to the first byte after this run
}
// This step is done: hand the result to whatever this sink wraps.
next().write(encoded);
}
How this code works: RleSink::write

The outer loop visits the input one run at a time; the inner loop measures how long the current run is.

  1. i is where the current run starts. run starts at 1, because the byte at i is a run of one by itself.
  2. The inner loop grows run while three things hold: there is a byte after the run (i + run < bytes.size()), the count still fits in one byte (run < 255), and that byte equals the first byte of the run. The first test comes first on purpose: && stops at the first false, so bytes[i + run] is never read past the end.
  3. The run is stored as two bytes, the count and the byte, and i jumps past the whole run.
  4. When i reaches the end, the encoded bytes go to next().write.

A trace for rle.write("aaab"), as in the first test:

i inner loop run appended
0 bytes[1], bytes[2] are a; bytes[3] is b 3 03, a
3 i + run is 4, the end: does not run 1 01, b
4 outer loop ends

So the next sink receives four bytes, 03 61 01 62 in hexadecimal. For 300 xs, the first run stops at 255 because of run < 255, giving ff 78; the second starts at i = 255 and runs to the end, 45 bytes, giving 2d 78. long_runs_are_split_at_255 checks exactly this.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

decorators.hpp
// XOR with a repeating key: a stand-in for encryption that is easy to
// check by hand. It is NOT secure. Each byte is combined with one byte of
// the key, k, 3, y, k, 3, y, ... for the key "k3y". XORing twice with the
// same key byte gives the original byte back, which is how xor_with in
// codec.hpp reads the data back.
class XorSink final : public SinkDecorator {
public:
// Takes the key by value and moves it into key_, so a caller who
// passes a temporary string pays for no extra copy.
XorSink(std::unique_ptr<Sink> next, std::string key); // throws for an empty key
void write(std::string_view bytes) override;
private:
std::string key_; // never empty: the constructor checks
// Index into key_ of the key byte for the next byte written. It is a
// member, not a local variable, so it carries on from one write to
// the next: writing "ab" then "cd" gives the same bytes as "abcd".
std::size_t position_ = 0; // the key byte for the next byte written
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

decorators.cpp
// The next sink goes to the base class, and the key is moved into key_.
// Then an empty key is refused: `% key_.size()` in write would divide by
// zero. If this throws, the sink that was handed over is destroyed too.
XorSink::XorSink(std::unique_ptr<Sink> next, std::string key)
: SinkDecorator{std::move(next)}, key_{std::move(key)} {
if (key_.empty()) {
throw std::invalid_argument{"the key must not be empty"};
}
}
// Mixes each byte with the next byte of the key and passes the result on.
// The incoming bytes are a read-only view, so they are first copied into
// a string this function may change.
void XorSink::write(std::string_view bytes) {
std::string mixed{bytes};
// `char& byte` is a reference to each character in turn, so assigning
// to byte changes the character inside mixed.
for (char& byte : mixed) {
// `^` is bitwise XOR. The two chars are promoted to int for it,
// and static_cast<char> turns the result back into a char.
byte = static_cast<char>(byte ^ key_[position_]);
// Step to the next key byte, wrapping round to 0 after the last:
// with "k3y", position_ goes 0, 1, 2, 0, 1, 2, ...
position_ = (position_ + 1) % key_.size();
}
next().write(mixed);
}
How this code works: XorSink::write across two writes

write copies the bytes into mixed, because a std::string_view is read-only, then changes each byte of the copy in place through char& byte. Each byte is XORed with key_[position_], and position_ moves on by one, wrapping to 0 after the last key byte.

position_ is a member, so it is not reset when write returns. Here is the_key_keeps_its_place_across_writes, with the key k3y (bytes 6b 33 79):

call byte position_ key byte result
write("ab") a 61 0 k 6b 0a
b 62 1 3 33 51
write("cd") c 63 2 y 79 1a
d 64 0 k 6b 0f

The stored bytes are 0a 51 1a 0f, the same as xor_with("abcd", "k3y"). If position_ were a local variable starting at 0 in each call, the second write would use k and 3 and store 08 57 instead, and xor_with could no longer read the data back.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

decorators.hpp
// Passes the bytes on unchanged, and counts them. It counts the bytes
// that reach it, so what it counts depends on where it sits in the chain:
// outermost, it counts what the app wrote; innermost, what is stored.
class CountingSink final : public SinkDecorator {
public:
explicit CountingSink(std::unique_ptr<Sink> next);
void write(std::string_view bytes) override;
std::size_t count() const { return count_; }
private:
std::size_t count_ = 0; // total bytes over every write so far
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

decorators.cpp
CountingSink::CountingSink(std::unique_ptr<Sink> next) : SinkDecorator{std::move(next)} {}
// Adds this write's size to the running total, then passes the very same
// bytes on: no copy, no change. The count goes up before next().write is
// called, so if a later sink throws, these bytes have already been counted.
void CountingSink::write(std::string_view bytes) {
count_ += bytes.size();
next().write(bytes);
}

Every write has the same shape: do this step’s work, then call next().write(...). None of them knows what next() is: a file, another decorator, or a whole chain.

  • RleSink changes the bytes and has no state of its own.
  • XorSink changes the bytes and has state: the place in the key carries on from one write to the next, so that two writes give the same bytes as one write of both. A test checks this.
  • CountingSink does not change the bytes; it only watches them. A decorator can add a step that has nothing to do with the bytes’ content.

Reading the data back is the reverse journey, with the steps undone in reverse order:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

codec.hpp
// Reading back what the decorators wrote. Undo the steps in the reverse
// of the order they were applied in. These are plain functions, not
// sinks: they take all the stored bytes at once and return the result.
//
// rle_decode turns each (count, byte) pair back into `count` copies of the
// byte. It throws std::invalid_argument if the input has an odd length (a
// count without its byte) or a count of 0, which RleSink never writes.
//
// xor_with XORs byte i with key[i % key.size()], starting at key byte 0.
// Because (b ^ k) ^ k == b, the same function both "encrypts" and
// "decrypts", as long as it starts where the XorSink started. It throws
// std::invalid_argument for an empty key.
std::string rle_decode(std::string_view encoded); // throws for an odd length or a zero run
std::string xor_with(std::string_view bytes, std::string_view key); // XOR undoes itself

interface (abstract class) Sink

the component: not copyable

Member functions

  • virtual void write(std::string_view bytes) = 0;

class MemorySink final

the concrete component: the end of every chain

Data members

  • std::string* out_; borrowed: must outlive the sink

Member functions

  • explicit MemorySink(std::string& out);

class SinkDecorator

the decorator base: owns the next sink

Data members

  • std::unique_ptr<Sink> next_; never null

Member functions

  • explicit SinkDecorator(std::unique_ptr<Sink> next); protected; throws if null
  • Sink& next(); protected

class RleSink final

compresses: run-length encoding

Member functions

  • explicit RleSink(std::unique_ptr<Sink> next);

class XorSink final

"encrypts": XOR with a repeating key; not secure

Data members

  • std::string key_; never empty
  • std::size_t position_; carries on across writes

Member functions

  • XorSink(std::unique_ptr<Sink> next, std::string key); throws for an empty key

class CountingSink final

watches: counts the bytes that reach it

Data members

  • std::size_t count_;

Member functions

  • explicit CountingSink(std::unique_ptr<Sink> next);
  • std::size_t count() const;

namespace global

not a real namespace: free functions at file scope

Functions

  • std::string rle_decode(std::string_view encoded); throws for bad data
  • std::string xor_with(std::string_view bytes, std::string_view key);
The sinks: the Sink interface, the MemorySink at the end of every chain, the decorator base, three decorators, and the functions that read the data back

The outline leaves out the write overrides of the concrete sinks.

  • The chain is owned from the outside in. main owns the outermost sink; each decorator owns the next one; the last decorator owns the MemorySink. Destroying the outermost sink destroys the whole chain. Nothing in it is shared, so std::unique_ptr says exactly what happens.
  • The chain is built from the inside out. The MemorySink is created first, then each decorator is created around the one before. So the last decorator written in the code is the first to see the bytes. Read the construction from the outside (the left) in.
  • The storage outlives the chain. MemorySink borrows the string, and main declares the string before the chain, so the chain is destroyed first.
  • A wrapped decorator’s own functions are hidden. Once CountingSink is inside the chain, main holds only a std::unique_ptr<Sink>, and Sink has no count(). main keeps a reference, counter, taken before the CountingSink was moved into the chain. It observes without owning, and stays valid as long as the chain does, because moving a std::unique_ptr does not move the object it points to.
  • A constructor that throws loses what it was given. The decorators take the next sink by value, so ownership passes at the call. If XorSink’s constructor then refuses an empty key, the sink it was given is destroyed with it. That is acceptable here: a caller who passes a bad key gets no chain either way, and keeps no references into it. Compare Composite, where a refused add had to leave the node with its caller.
  • Stateful decorators cannot be shared. An XorSink remembers its place in the key, so one XorSink must not be used for two different files. Each file gets its own chain.
  • Threads: nothing here locks. One chain belongs to one thread at a time.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// A chain of one decorator. std::make_unique<MemorySink>(compressed)
// creates a MemorySink on the heap and returns the std::unique_ptr
// that owns it; RleSink's constructor takes that ownership. rle_only
// itself is a local variable, destroyed (with its MemorySink) at the
// end of main.
std::string compressed;
RleSink rle_only{std::make_unique<MemorySink>(compressed)};
rle_only.write(record);
std::cout << "compressed: " << hex(compressed) << "\n";
// Count, then compress, then encrypt. The chain is built from the
// file outwards; the outermost sink sees the bytes first.
// C++ evaluates the innermost make_unique first: MemorySink, then the
// XorSink around it, then RleSink, then CountingSink. Each one takes
// ownership of the sink created just before it.
std::string file; // declared before the chain, so it outlives it
auto counting = std::make_unique<CountingSink>(
std::make_unique<RleSink>(std::make_unique<XorSink>(std::make_unique<MemorySink>(file), key)));
// Take a reference to the CountingSink now, while `counting` still
// has the type std::unique_ptr<CountingSink>: once it is stored as a
// std::unique_ptr<Sink>, count() can no longer be reached through it.
const CountingSink& counter = *counting; // observer: the chain owns it
// std::move hands ownership to `sink` and leaves `counting` empty. The
// CountingSink itself stays where it is on the heap, so `counter`
// still refers to it.
std::unique_ptr<Sink> sink = std::move(counting);
// One call. Each sink does its step and calls the next one's write.
sink->write(record);
std::cout << "compress, then encrypt: " << counter.count() << " in, " << file.size() << " out\n";
// Undo in reverse: the last step applied (XOR) is undone first.
std::cout << " read back: " << rle_decode(xor_with(file, key)) << "\n";
// The same decorators in the other order.
// Here XorSink is outermost, so it sees the record first and RleSink
// compresses the XORed bytes.
std::string other;
std::unique_ptr<Sink> reordered =
std::make_unique<XorSink>(std::make_unique<RleSink>(std::make_unique<MemorySink>(other)), key);
reordered->write(record);
std::cout << "encrypt, then compress: " << record.size() << " in, " << other.size() << " out\n";
// Reading back follows this chain's order in reverse: decompress
// first, then undo the XOR.
std::cout << " read back: " << xor_with(rle_decode(other), key) << "\n";
How this code works: One write through the chain

Building it. In the second chain, the innermost std::make_unique runs first, because a function’s arguments are worked out before the function is called. So the MemorySink is created first, then the XorSink that takes ownership of it, then the RleSink, then the CountingSink. counting owns the outermost one.

Keeping a way in. counter is a reference taken while counting still has the type std::unique_ptr<CountingSink>. The next line moves the pointer into sink, a std::unique_ptr<Sink>, and through that type there is no count(). Moving a std::unique_ptr moves only the pointer: the CountingSink stays at the same address, so counter stays valid for as long as the chain lives.

The single call sink->write(record). Each sink does its step, then calls next().write on the one it owns:

sink receives does passes on
CountingSink the 24-byte record count_ becomes 24 the same 24 bytes
RleSink the 24 bytes three runs of 8 08 61 08 62 08 63
XorSink those 6 bytes XOR with k 3 y k 3 y 63 52 71 09 3b 1a
MemorySink those 6 bytes appends them to file (nothing: the end)

So counter.count() is 24 and file.size() is 6. Reading back undoes the last step first: xor_with(file, key) gives 08 61 08 62 08 63 again, and rle_decode turns that into the record.

The other order. In reordered, XorSink is outermost. It turns the record into 0a 52 18 0a 52 18 0a 52 1b 09 51 ..., where no byte equals the one beside it. RleSink then sees 24 runs of length 1 and writes two bytes for each: 48.

Expected output
record: aaaaaaaabbbbbbbbcccccccc (24 bytes)
before: 6 bytes written
compressed: 08 61 08 62 08 63
compress, then encrypt: 24 in, 6 out
read back: aaaaaaaabbbbbbbbcccccccc
encrypt, then compress: 24 in, 48 out
read back: aaaaaaaabbbbbbbbcccccccc

Read the output against the requirements:

  • compressed: 08 61 08 62 08 63 is eight as (61 in hexadecimal), eight bs, and eight cs: 24 bytes as 6 (FR-1).
  • compress, then encrypt: 24 in, 6 out. The CountingSink is the outermost sink, so it counts the 24 bytes the app wrote, not the 6 that were stored (FR-3).
  • read back undoes the steps in reverse: decrypt, then decompress, and the record comes back (FR-4).
  • encrypt, then compress: 24 in, 48 out. The same two decorators in the other order make the record twice as large. XOR with a three-byte key turns aaaaaaaa into a repeating three-byte pattern with no two equal bytes next to each other, so every run is one byte long, and run-length encoding writes two bytes for each.

The order of decorators is part of the design, not a detail. Compress before you encrypt: good encryption makes its output look random, and random bytes do not compress.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_stream.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false; LLD_CHECK_EQ(actual, expected) does the same
// for actual == expected and prints both values; and
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws
// that type of exception. They come from the test header lld_test.hpp.
//
// static_assert checks a claim while the program compiles, so these two
// cannot fail at run time: the build would stop first. Sink is abstract
// (no plain Sink can be created), and a decorator cannot be copied.
static_assert(std::is_abstract_v<Sink>);
static_assert(!std::is_copy_constructible_v<RleSink>);
// Each decorator on its own, wrapped round a MemorySink so that the
// test can read exactly what it passed on.
LLD_TEST(each_decorator_changes_or_watches_the_bytes) {
std::string out;
RleSink rle{std::make_unique<MemorySink>(out)};
rle.write("aaab");
// Three a's, then one b. The literal is split into pieces because
// "\x03a" would be read as the single hex byte 0x3a; the compiler
// joins neighbouring literals into one string.
const std::string expected{"\x03" "a" "\x01" "b"};
LLD_CHECK_EQ(out, expected);
// XorSink changes the bytes, and xor_with with the same key gets the
// original back.
std::string mixed;
XorSink xor_sink{std::make_unique<MemorySink>(mixed), "k3y"};
xor_sink.write("hello");
LLD_CHECK(mixed != "hello");
LLD_CHECK_EQ(xor_with(mixed, "k3y"), std::string{"hello"});
// CountingSink passes the bytes on unchanged and counts all 5.
std::string same;
CountingSink counting{std::make_unique<MemorySink>(same)};
counting.write("hello");
LLD_CHECK_EQ(same, std::string{"hello"});
LLD_CHECK_EQ(counting.count(), std::size_t{5});
}
// Two chains of the same two decorators, in opposite orders. Each one
// must read back to the record when its steps are undone in reverse.
LLD_TEST(the_decorators_combine_in_either_order) {
const std::string record = "aaaaaaaabbbbbbbbcccccccc";
std::string first;
RleSink compress_then_encrypt{std::make_unique<XorSink>(std::make_unique<MemorySink>(first), "k3y")};
compress_then_encrypt.write(record);
LLD_CHECK_EQ(rle_decode(xor_with(first, "k3y")), record);
std::string second;
XorSink encrypt_then_compress{std::make_unique<RleSink>(std::make_unique<MemorySink>(second)), "k3y"};
encrypt_then_compress.write(record);
LLD_CHECK_EQ(xor_with(rle_decode(second), "k3y"), record);
}
// The same two chains, checked by size: compressing first stores 3 runs
// as 6 bytes; XORing first leaves no two equal bytes side by side, so all
// 24 bytes become runs of 1, stored as 48 bytes.
LLD_TEST(the_order_changes_the_result) {
const std::string record = "aaaaaaaabbbbbbbbcccccccc";
std::string first;
RleSink compress_then_encrypt{std::make_unique<XorSink>(std::make_unique<MemorySink>(first), "k3y")};
compress_then_encrypt.write(record);
std::string second;
XorSink encrypt_then_compress{std::make_unique<RleSink>(std::make_unique<MemorySink>(second)), "k3y"};
encrypt_then_compress.write(record);
LLD_CHECK_EQ(first.size(), std::size_t{6});
LLD_CHECK_EQ(second.size(), std::size_t{48}); // XOR broke up every run
}
// A count must fit in one byte, so a run of 300 is stored as 255 + 45:
// 0xff is 255 and 0x2d is 45. Reading back gives all 300 again.
LLD_TEST(long_runs_are_split_at_255) {
std::string out;
RleSink rle{std::make_unique<MemorySink>(out)};
// std::string(300, 'x') is 300 copies of 'x'. Round brackets matter
// here: with braces, std::string would treat 300 and 'x' as a list of
// two characters, and since 300 does not fit in a char, the line would
// not even compile.
rle.write(std::string(300, 'x'));
const std::string expected{"\xff" "x" "\x2d" "x"};
LLD_CHECK_EQ(out, expected);
LLD_CHECK_EQ(rle_decode(out), std::string(300, 'x'));
}
// "ab" uses key bytes k and 3; the second write must carry on with y and
// k, not start again at k. So two writes match one write of "abcd".
LLD_TEST(the_key_keeps_its_place_across_writes) {
std::string out;
XorSink xor_sink{std::make_unique<MemorySink>(out), "k3y"};
xor_sink.write("ab");
xor_sink.write("cd");
LLD_CHECK_EQ(out, xor_with("abcd", "k3y"));
}
// CountingSink is put INSIDE an RleSink. The test keeps a reference to it
// before handing it over, and reads the count through that reference.
LLD_TEST(a_wrapped_decorator_stays_reachable_through_an_observer) {
std::string out;
auto counting = std::make_unique<CountingSink>(std::make_unique<MemorySink>(out));
const CountingSink& counter = *counting; // taken while the type is still known
// `chain` now owns the CountingSink; `counting` is empty, but the
// object did not move, so `counter` is still valid.
RleSink chain{std::move(counting)};
// RleSink turns "aaaa" into 2 bytes (04 'a') before CountingSink sees it.
chain.write("aaaa");
LLD_CHECK_EQ(counter.count(), std::size_t{2}); // it counts what reaches it
}
// The two constructor checks: a null next sink (nullptr becomes an empty
// std::unique_ptr), and an empty key.
LLD_TEST(a_decorator_needs_a_sink_and_a_key) {
LLD_CHECK_THROWS(RleSink{nullptr}, std::invalid_argument);
std::string out;
LLD_CHECK_THROWS(XorSink(std::make_unique<MemorySink>(out), ""), std::invalid_argument);
}
// rle_decode refuses data RleSink could never have written: a count with
// no byte after it (odd length), and a run of length 0.
LLD_TEST(bad_run_length_data_is_refused) {
LLD_CHECK_THROWS(rle_decode("\x02"), std::invalid_argument);
// The 2 gives the length. Without it, the string would stop at the
// first '\0' byte and be empty.
const std::string zero_run{"\x00" "a", 2};
LLD_CHECK_THROWS(rle_decode(zero_run), std::invalid_argument);
}
  • Each decorator is tested on its own, wrapped around a MemorySink. RecordWriter could test compression alone too, but only by going through the class that also holds every other step.
  • the_order_changes_the_result pins the 6 against 48 bytes.
  • the_key_keeps_its_place_across_writes checks XorSink’s state.
  • a_wrapped_decorator_stays_reachable_through_an_observer puts CountingSink inside an RleSink, and it counts 2 bytes for a write of aaaa: a decorator sees only what reaches it.
  • RleSink encodes each write on its own, so a run split across two writes is stored as two runs. The data can still be read back, but it compresses less well than it could. A real compressor buffers, and then the interface needs a flush or finish so that the last bytes are not lost, which every decorator would have to pass on.
  • Run-length encoding makes data with few repeats larger, up to twice the size. Real compression formats fall back to storing such data as it is.
  • rle_decode and xor_with read a whole string at once. A real reader would be a chain of its own, of “sources” wrapping each other in the reverse order.
  • A wrapper function. When only one call needs a step, a function that does the step and calls the original is enough. When the interface has one function, a std::function can be wrapped in a lambda that captures the next one, which is Decorator without the classes. A step with state, like XorSink’s place in the key, needs a mutable lambda, and std::function requires a copyable callable, so the lambda cannot capture a std::unique_ptr.
  • Decorating at compile time. A decorator can be a class template that holds the next sink by value, such as Rle<Xor<MemorySink>>. There are no virtual calls and no heap allocations, but each chain is a separate type fixed when the program is compiled. Choosing from configuration would mean compiling every combination the customers might ask for, and their number grows fast.
  • The standard library’s streams make the same idea possible. A std::ostream writes through a std::streambuf; a custom std::streambuf that holds another std::streambuf, changes the bytes, and passes them on is a decorator. The standard library does not provide such a filtering buffer itself.
  • Optional steps that combine freely: compression, encryption, checksums; logging, timing, retrying, or caching around a service; borders and scroll bars around a widget.
  • The order of the steps varies, or is chosen from configuration.
  • The class being extended cannot or should not change: it comes from a library, or several teams depend on it.
  • Each step should be testable alone, against a simple fake of the interface.
  • The steps are fixed. If every record is always compressed and then encrypted, one function that does both is clearer, and a chain of objects is ceremony.
  • The interface is wide. A decorator must pass on every function of the interface. With twenty functions, each decorator is mostly forwarding code, and a forgotten one silently skips the step. Narrow the interface first, or decorate a smaller one.
  • The step must see inside the object. A decorator sees only the interface. If the step needs private data, it belongs in the class, or the class needs a different design.
  • Callers need the concrete type. A decorated object is a different object. Code that compares addresses or uses dynamic_cast to find the concrete class sees the outermost decorator, and gets a different answer.
  • More objects. Each step is one allocation when the chain is built, and one virtual call per write. RleSink and XorSink also build a new std::string on every write. For a backup tool this is nothing next to the work of compressing; for very small, very frequent calls, measure.
  • The order is easy to get wrong, as the output shows, and the compiler cannot check it. Build chains in one place, with the order written down, and test the chains that ship.
  • Debugging steps through every layer. A stack trace through four decorators is longer than one through a single function.
  • The interface is harder to change. Adding a function to Sink means every decorator must handle it, which is why SinkDecorator exists.
  • Decorators that change the meaning of the interface. A “decorator” whose write sometimes drops data, or that needs the client to call extra functions in a certain order, breaks the promise that it can be used wherever a Sink can. If the interface must change, that is an Adapter.
  • Decorators that depend on each other. A CountingSink that only works when placed right after an RleSink is not a free step. If two steps always go together, make them one decorator.
  • Building chains everywhere. If every caller builds its own chain, the order is decided in many places. Build them in one function, or in main.
  • std::shared_ptr for the next sink “in case someone needs it”. Two chains sharing one stateful sink interleave their bytes. Share only when there is a real reason, and then say so in the types.
  • “Add a checksum.” A new decorator, ChecksumSink. None of the existing classes change, and only the code that builds the chain decides where it goes.
  • “Send the bytes over the network.” A new concrete component, SocketSink. Every decorator works with it unchanged.
  • “Use real compression.” Replace RleSink’s body with a call to a compression library. It will need to buffer, which means adding a finish step to Sink. SinkDecorator can forward it for the decorators that do not buffer; a buffering decorator must override it to write out its own buffer first, and then forward it.
  • “Let customers choose steps in a config file.” A function that reads the configuration and builds the chain from the inside out. This is exactly what the before-version could not do.

Exercise: Reorder the decorators and explain

Answer using the example’s record (aaaaaaaabbbbbbbbcccccccc, 24 bytes) and key (k3y).

  1. The storage team wants to bill by the bytes that reach the file, not the bytes the app wrote. Where should CountingSink go in the compress-then-encrypt chain, and what will it count?
  2. Explain in your own words why encrypt-then-compress writes 48 bytes.
  3. A colleague reads back compress-then-encrypt output with xor_with(rle_decode(file), key). What happens, and why is no error reported?
  4. A ChecksumSink must detect damage to the stored bytes. Where in the chain should it go? Where would it go if it had to check that the record was decrypted correctly instead?
Show the explained answer

1. Innermost, wrapped directly around the MemorySink:

std::string file;
// Built inside out: the CountingSink wraps the MemorySink directly, so it
// sees exactly the bytes that are stored.
auto counting = std::make_unique<CountingSink>(std::make_unique<MemorySink>(file));
const CountingSink& stored = *counting; // observer: the chain owns it
// XorSink takes ownership of the CountingSink; RleSink, outermost, wraps
// the XorSink. A write now goes RleSink, XorSink, CountingSink, MemorySink.
RleSink chain{std::make_unique<XorSink>(std::move(counting), "k3y")};
chain.write(record);
// stored.count() is 6: RLE made 6 bytes, and XOR keeps the length

It counts 6, the bytes after compression and encryption. The same class counts something different depending only on where it is.

2. Run-length encoding gains only when equal bytes are next to each other. XOR with k3y mixes each a with k, then 3, then y, so the 24 bytes become a three-byte repeating pattern in which no byte equals its neighbour. Every run has length 1, and each costs two bytes: 48.

3. The steps are undone in the wrong order. rle_decode reads the encrypted bytes as counts: the count 08 was XORed with k, y, and 3 in turn, and reads as 99, 113, and 59. So it produces 271 bytes, and xor_with turns them into 271 wrong bytes. Nothing fails, because XOR accepts any bytes and these counts happen to be valid: no count became 0, and XOR keeps the length, so the six bytes still made three pairs. A scratch program confirmed the 271 bytes. This is why the reading code should be built from the same configuration as the writing chain, and why a checksum helps.

4. To detect damage to stored bytes, the checksum must cover what is stored: put it innermost, next to the MemorySink, after encryption. To check that decryption gave back the right record, it must cover the original bytes: put it outermost, before compression, and check it after reading back. Both are reasonable, and they answer different questions, which is the point: the position of a decorator is part of what it means. A checksum catches accidental damage only. Someone who changes the stored bytes on purpose can recompute it; protecting against that needs authenticated encryption or a message authentication code from a cryptography library.

  • Adapter changes an object’s interface; Decorator keeps it and adds behaviour. See Adapter.
  • Composite has the same shape, a component that holds components, but a composite holds many children to make a group, and a decorator holds exactly one to add a step. See Composite.
  • Proxy also wraps an object behind the same interface, but to control access to it (loading it late, checking permissions, or reaching it over a network), not to add steps. See Proxy and Decorator vs Proxy.
  • Chain of Responsibility also passes a call along a chain of objects, but each handler decides whether it is the one that handles the request, and the request may be handled by none of them. A decorator chain always ends in one real component, and each decorator adds to the work rather than claiming it (a caching decorator may skip the inner call, but only to give the same answer faster). See Chain of Responsibility.
  • Strategy changes how an object does its work from the inside, by swapping a part it uses; Decorator changes it from the outside, by wrapping. See Strategy.
  • Decorator adds a step to an object’s work by wrapping it in an object with the same interface, which does its step and passes the call on.
  • Because decorators are components themselves, they stack in any number and any order, and the client cannot tell.
  • In C++, let each decorator own the next object through std::unique_ptr; build the chain from the inside out, and keep an observer reference if you need a wrapped decorator’s own functions.
  • Order matters: compress-then-encrypt stored 6 bytes, and encrypt-then-compress stored 48. Build chains in one place.
  • Keep the interface narrow, because every decorator must pass on every function of it. For fixed steps, one plain function is simpler.