Decorator vs Proxy
What you will learn on this page
Section titled “What you will learn on this page”- 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.
The short answer
Section titled “The short answer”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.
RleSinkcompresses the bytes before passing them on;CountingSinkcounts 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.
LazyImageloads 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.
Side by side
Section titled “Side by side”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).
// 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).
// 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.
- Where the wrapped object comes from.
SinkDecorator’s constructor takes astd::unique_ptr<Sink>: the caller builds the next sink and hands it over.LazyImage’s constructor takes a catalogue entry and a store, not anImage: the proxy fetches its real image itself, later, by callingstore_->load(...). - Whether the pointer may be null.
SinkDecorator’s constructor throwsstd::invalid_argumentfor a null pointer, sonext()can use*next_with no check: a decorator always has somewhere to write.LazyImage’sreal_starts null, is filled on the first call topixels(), and is null again afterunload().loaded()simply asks whether it is null. mutableon the proxy’s pointer.pixels()isconst, because to the caller, reading pixels does not change the image. Loading is a hidden detail, soreal_ismutable, which lets aconstfunction fill it in. A decorator needs no such thing: itsnext_is set once in the constructor and never changes.- Who may reach the wrapped object.
SinkDecoratorgives derived decoratorsnext(), 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.LazyImagekeepsreal()private, and addsloaded()andunload(), which are not part ofImage: 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 nullexplicit SinkDecorator(std::unique_ptr<Sink> next);protected; throws if nullSink& 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
class LazyImage final
a proxy: same answers, loaded late; derives from Image
Data members
CatalogueEntry entry_;copied: name and size, known without loadingImageStore* store_;borrowed: must outlive the proxymutable 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 loadsSize size() const override;never loadsstd::span<const std::uint8_t> pixels() const override;loads on first usebool loaded() const;void unload();frees the pixels; spans from pixels() dangle
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 |
Questions that tell them apart
Section titled “Questions that tell them apart”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"]- 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. - 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
LazyImageout and give the galleryBitmaps: the gallery shows the same pictures, only after a longer start. - Does it add work? Changing the results (compressing,
encrypting) or doing something extra (counting, logging, timing) is
a decorator. Take
RleSinkout of the chain and the file is bigger; takeCountingSinkout and there is no count. - 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.
Ownership in C++
Section titled “Ownership in C++”The C++ choices follow from the purpose:
- A decorator owns what it is given.
SinkDecoratortakes astd::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.
LazyImageownsreal_, which is null until needed; it borrows theImageStore, which must outlive every proxy.real_ismutablebecause loading is an access detail, invisible to aconstcaller; that also means two threads callingpixels()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.
The cases that blur
Section titled “The cases that blur”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.
When neither is needed
Section titled “When neither is needed”- 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
Section titled “Exercise”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.
TimingSinkwraps aSink, measures how long eachwritetakes, and adds the time to aMetricsobject that the program reads once a minute.RemoteInventoryimplements the shop’sInventoryinterface by sending each call to a stock server and returning its answer.CachedPriceListwraps aPriceList, 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.