Video in progress

Strong Junior 🧭 Design patterns

Decorator and Proxy look very much alike. What is the difference?

Their structure is almost the same: both wrap an object with the same interface. The difference is in intent: a Decorator adds new functionality and is usually assembled as a chain, while a Proxy controls access to the real object (lazy, permissions, cache, remote).

📖 Answer

It's hard to tell them apart from the code, so look at the intent.

Decorator Proxy
What for Enriching behavior Controlling access
Who creates it Often the client assembles it Usually a framework or factory, the client doesn't know
How many layers Several, and the order matters Often just one
The real object Always called, the result is modified May not be called at all (cache, rejection)

Examples:

  • new BufferedReader(new InputStreamReader(in)): you add the layers yourself, so this is a Decorator.
  • A Spring bean with a @Cacheable method: you think you're calling UserService, but really a CGLIB proxy is returning the result from the cache. That's a Proxy.

In an interview, it's enough to say "the structure is the same, the intent is different" and give one Spring example. Some authors don't draw the line strictly at all, and mentioning that is fine too.