Skip to content

Decorator vs Proxy

Difficulty: Intermediate

Prerequisites

Key concepts

  • decorator pattern
  • proxy pattern
  • wrapper
  • ownership
  • choosing a pattern
  • Why Decorator and Proxy look the same in code, and what actually separates them: the purpose of the wrapper.
  • The questions that tell them apart when you meet a wrapper in real code, or are about to write one.
  • How each one usually creates, owns, or borrows the object it wraps, in C++.
  • The cases that sit between the two, and when neither is needed.

Both put an object in front of another object with the same interface, so the caller cannot tell the wrapper from the real thing.

  • A decorator adds work: it changes or watches what the wrapped object does. RleSink compresses the bytes before passing them on; CountingSink counts them. The caller gets different or extra results, and usually asked for them.
  • A proxy controls access: it decides when, whether, or where the real object is reached. LazyImage loads the real image only when its pixels are first needed. The caller gets the same answers, but at a different time, at a different cost, or only if allowed.

If you remove a decorator, the program does less (no compression, no count). If you remove a proxy, the program does the same thing, but loads every image up front, or lets everyone in.

The two base classes, from the two examples:

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_;
};

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

lazy_image.hpp
// A proxy that stands in for an image and loads it only when its pixels
// are first needed. The name and size come from the catalogue.
// It derives from Image, the same interface as the real Bitmap, so any
// code written for Image accepts a LazyImage without knowing it is one.
// Making one is cheap and cannot fail on a missing file: nothing is read
// until pixels() is called.
class LazyImage final : public Image {
public:
// Keeps its own copy of the catalogue entry (taken by value, then moved
// in), and remembers which store to load from. Loads nothing.
LazyImage(CatalogueEntry entry, ImageStore& store);
// These two answer from the copied catalogue entry, so they never
// touch the store, even for a file that is missing.
const std::string& name() const override { return entry_.name; }
Size size() const override { return entry_.size; } // never loads
// Loads the real image the first time, then reuses it. Throws if the
// load fails or the file's size disagrees with the catalogue; after a
// throw the proxy is still unloaded, and the next call tries again.
std::span<const std::uint8_t> pixels() const override; // loads on first use
// Not part of Image: only code that knows it holds a LazyImage (a
// memory manager, or a test) can ask this or call unload().
bool loaded() const { return real_ != nullptr; }
// Frees the pixels; they are loaded again if needed. Any span from
// pixels() dangles after this.
// reset() destroys the image real_ owns and leaves real_ null. It is
// not const: it needs a LazyImage the caller may change.
void unload() { real_.reset(); }
private:
// The loaded image, loading it first if real_ is still null.
const Image& real() const;
CatalogueEntry entry_; // the proxy's own copy: name and expected size
// A plain pointer here means "borrowed": the proxy uses the store but
// never deletes it.
ImageStore* store_; // borrowed: must outlive the proxy
// The real subject, once loaded. std::unique_ptr: the proxy is its only
// owner and frees it when the proxy is destroyed or unloads. `mutable`
// lets the const pixels() fill it in; the page explains why that is
// allowed here.
mutable std::unique_ptr<Image> real_; // owned; null until first needed
};
How this code works: Reading the two classes line by line

Both classes have the same skeleton: : public the interface, and a std::unique_ptr to another object of that interface. The intent shows in four places around that pointer.

  1. Where the wrapped object comes from. SinkDecorator’s constructor takes a std::unique_ptr<Sink>: the caller builds the next sink and hands it over. LazyImage’s constructor takes a catalogue entry and a store, not an Image: the proxy fetches its real image itself, later, by calling store_->load(...).
  2. Whether the pointer may be null. SinkDecorator’s constructor throws std::invalid_argument for a null pointer, so next() can use *next_ with no check: a decorator always has somewhere to write. LazyImage’s real_ starts null, is filled on the first call to pixels(), and is null again after unload(). loaded() simply asks whether it is null.
  3. mutable on the proxy’s pointer. pixels() is const, because to the caller, reading pixels does not change the image. Loading is a hidden detail, so real_ is mutable, which lets a const function fill it in. A decorator needs no such thing: its next_ is set once in the constructor and never changes.
  4. Who may reach the wrapped object. SinkDecorator gives derived decorators next(), a reference they can write to but cannot take away, because each decorator’s job is to do its step and then pass the bytes on. LazyImage keeps real() private, and adds loaded() and unload(), which are not part of Image: only code that knows it holds a proxy, such as a memory manager or a test, can ask about loading.

class SinkDecorator

abstract base of every decorator; derives from Sink

Data members

  • std::unique_ptr<Sink> next_; owned; given by the client; never null
  • explicit SinkDecorator(std::unique_ptr<Sink> next); protected; throws if null
  • Sink& next(); protected: for derived decorators

class CountingSink final

a decorator: same bytes, plus a count

Data members

  • std::size_t count_;

Member functions

  • explicit CountingSink(std::unique_ptr<Sink> next);
  • void write(std::string_view bytes) override; counts, then next().write(bytes)
  • std::size_t count() const; an extra query the Sink interface does not have
Decorator: CountingSink wraps any Sink it is given, and owns it

class LazyImage final

a proxy: same answers, loaded late; derives from Image

Data members

  • CatalogueEntry entry_; copied: name and size, known without loading
  • ImageStore* store_; borrowed: must outlive the proxy
  • mutable std::unique_ptr<Image> real_; owned; loaded by the proxy from the store; null until needed

Member functions

  • LazyImage(CatalogueEntry entry, ImageStore& store);
  • const std::string& name() const override; never loads
  • Size size() const override; never loads
  • std::span<const std::uint8_t> pixels() const override; loads on first use
  • bool loaded() const;
  • void unload(); frees the pixels; spans from pixels() dangle
Proxy: LazyImage loads its real image when first needed, and owns it

The structure is almost the same: a class that derives from the interface and holds a std::unique_ptr to another object of that interface. What differs is everything around that pointer.

Question Decorator (CountingSink, RleSink) Proxy (LazyImage)
What is it for? add a step: compress, encrypt, count control access: load late, free, check, cache
Who creates the wrapped object? the client, which passes it in often the proxy, here loaded from the store when first needed
Is the wrapped object always there? yes; the constructor refuses null no; real_ is null until it is needed, and again after unload
Does the result change? yes, or something extra is done: compressed bytes, a count, a log line no: the same pixels, only later
How many are stacked? often several, and their order matters (compress, then encrypt) usually one, sometimes two (a protection proxy around a lazy one)
Does the client know it has a wrapper? yes: it built the chain, and may keep a reference (to read the count) ideally not: only open_gallery builds them; listing and average_grey take Image and never ask
Three questions, asked in order, about a wrapper around another object
Text description of the diagram

A decision flowchart with three questions and four outcomes. The first question: can the wrapper be used wherever the object inside it is used? If not, it is closer to an adapter than to either of these. If so, ask the second question: does it decide when, whether, or where the real object is reached, while the answers stay the same? If yes, it is a proxy. If no, ask the third question: does it add work, by changing the results or doing something extra such as counting or logging? If yes, it is a decorator. If no, probably no wrapper is needed at all. A fourth question, about who creates the wrapped object, is a clue explained in the text, not a branch.

Diagram source (Mermaid)
flowchart TD
Q1{"Can the wrapper be used<br/>wherever the object<br/>inside is used?"}
Q1 -- "no" --> A["Closer to an Adapter"]
Q1 -- "yes" --> Q2{"Does it decide when, whether,<br/>or where the real object<br/>is reached, with the<br/>same answers?"}
Q2 -- "yes" --> P["Proxy"]
Q2 -- "no" --> Q3{"Does it add work:<br/>change the results, or do<br/>something extra such as<br/>counting or logging?"}
Q3 -- "yes" --> D["Decorator"]
Q3 -- "no" --> N["Probably no wrapper is needed"]
  1. Can it be used wherever the inner object is used? A decorator or proxy implements the same interface, and may add a few extra functions such as count(). If the wrapper offers a different interface instead, it is closer to an Adapter.
  2. Does it decide when, whether, or where the real object is reached, with the same answers? Loading late, refusing a caller, answering from a cache, or sending the call to another process are all access decisions, and that is what a proxy is for. Take LazyImage out and give the gallery Bitmaps: the gallery shows the same pictures, only after a longer start.
  3. Does it add work? Changing the results (compressing, encrypting) or doing something extra (counting, logging, timing) is a decorator. Take RleSink out of the chain and the file is bigger; take CountingSink out and there is no count.
  4. Who creates the wrapped object? This is a clue, not a rule. A decorator is nearly always given the object, because the client chooses what to wrap. A lazy proxy obtains its own, from the store, because getting it late is the whole point. But a protection proxy, like the one in the Proxy page’s exercise, is given its object, just as a decorator is.

The C++ choices follow from the purpose:

  • A decorator owns what it is given. SinkDecorator takes a std::unique_ptr<Sink>, so a chain is built from the inside out and destroyed from the outside in; it refuses null, so every decorator always has something to pass the bytes to. If the client wants to read a decorator’s extra state, such as the count, it keeps a reference before handing ownership to the chain, and must not use it after the chain is gone.
  • A lazy proxy owns what it creates, and borrows what it creates it from. LazyImage owns real_, which is null until needed; it borrows the ImageStore, which must outlive every proxy. real_ is mutable because loading is an access detail, invisible to a const caller; that also means two threads calling pixels() on one proxy at once need a lock and a thread-safe store, as the Proxy page explains.
  • A proxy for an object others also use borrows it, by reference or pointer, and must not outlive it: a proxy in front of a shared connection, for example.

Some wrappers fit both descriptions, and teams name them differently. That is fine, as long as the code says what it does.

  • Caching. A wrapper that remembers answers is usually called a caching proxy: it decides whether the real object is asked at all. But if the cache can return stale answers, callers can notice it, and it is changing results, like a decorator. Whatever you call it, document how stale an answer can be.
  • Logging and timing. A wrapper that writes every call to a log changes no result, so a caller cannot tell it is there. It is still a decorator: it adds work (question 3) and controls nothing (question 2). Many libraries call this a logging proxy; by the questions on this page it is a decorator, because it controls nothing. It is easy to mistake for “no wrapper needed”, because the work it adds is for someone other than the caller.
  • Retrying. A wrapper that retries a failed call three times decides how often the real object is reached, which sounds like a proxy, but it also changes what callers see: fewer failures, and calls that sometimes take three times as long. It is often described either way; what matters is that retrying is only safe for calls that can be repeated (idempotent calls), such as reading a price, and not for charging a card twice.
  • Remote objects. A class that implements an interface by sending each call over the network, with no local object inside it at all, is a remote proxy: it stands in for an object in another process.
  • The behaviour is always wanted. If every sink must count its bytes, put the count in the sink. A wrapper earns its place when the step is optional or combined differently in different places.
  • There is only one place that calls it. A function that loads an image when needed, at the one place that needs it, is simpler than a proxy class.
  • The interface is large. A wrapper must forward every function. With twenty functions and one to change, it is a lot of code that can fall out of step with the interface; consider whether the change belongs in the class itself, or in the code that calls it.

Exercise: Classify three wrappers

Each of these classes implements the same interface as the object it stands for. For each, say whether it is a decorator or a proxy, using the questions above, and say what it should own.

  1. TimingSink wraps a Sink, measures how long each write takes, and adds the time to a Metrics object that the program reads once a minute.
  2. RemoteInventory implements the shop’s Inventory interface by sending each call to a stock server and returning its answer.
  3. CachedPriceList wraps a PriceList, and remembers each price it looks up for 60 seconds.
Show the explained answer

1. A decorator. It offers the same interface (question 1), it controls nothing about when or whether the sink is reached (question 2), and it adds work: timing each call (question 3). Callers see the same bytes written; the timings are for someone else, as with logging. It should own the Sink it wraps, as SinkDecorator does, and borrow the Metrics object, which the program owns and reads, and which must outlive the sink.

2. A proxy, a remote one. It decides where the real inventory is reached: in another process. There is no local object inside it to own. It owns its connection to the server, or borrows a shared one; and its interface must make room for failures that a local inventory never has, such as timeouts.

3. Usually called a caching proxy: it decides whether the real price list is asked at all (question 2). But for up to 60 seconds it can return a price that has already changed, so the answers are not always the same. Strictly, it fails question 2, and question 3 calls it a decorator that changes results. The name matters less than the decision: write down that prices may be up to 60 seconds old, and check that every caller can accept that. If it is given a price list that only it uses, it owns it, as a decorator would; if other code also uses that price list, it borrows it; if it opens the price list itself, when first needed, it owns that, as LazyImage does.