Design Patterns interview question · Most asked

What is the Decorator pattern? How is it different from inheritance?

Summary

Decorator wraps an object in another object with the same interface that adds behaviour before or after delegating. Unlike inheritance, decorators are combined at runtime and stack in any order, so you don't need a subclass for every combination of features.

Longer Answer

Typical uses are cross-cutting concerns: logging, caching, retries, metrics, authorization, compression. LoggingFetcher(CachingFetcher(RetryFetcher(http))) composes three features without changing HttpFetcher. Order matters: logging outside the cache logs every call; inside it, only real fetches.

Java I/O streams are the textbook example; Python's @decorator applies the same idea to functions; HTTP middleware is a decorator chain around a handler.

Code Example

class Http:
    def get(self, url):
        return f"<{url}>"


class Logged:  # decorator: same get(), adds logging
    def __init__(self, inner):
        self.inner = inner

    def get(self, url):
        print(f"GET {url}")
        return self.inner.get(url)


class Cached:  # decorator: same get(), adds caching
    def __init__(self, inner):
        self.inner, self.cache = inner, {}

    def get(self, url):
        if url not in self.cache:
            self.cache[url] = self.inner.get(url)
        return self.cache[url]


client = Cached(Logged(Http()))  # logging inside the cache: only real fetches are logged
print(client.get("/a"))
print(client.get("/a"))

Key Points

  • Same interface, wraps and delegates.
  • Adds behaviour without changing the class.
  • Stackable at runtime; order matters.
  • Java I/O streams, Python decorators, middleware.

Deep dive: Design Patterns, Explained Simply: Decorator

Explanation

What interviewers look for

Same-interface wrapping, runtime stacking, a cross-cutting example, and awareness that order matters.

Follow-up questions

  • How is a Decorator different from a Proxy?
  • What problems do deep decorator stacks cause?

More most-asked Design Patterns questions

← All Design Patterns questions