Skip to the page

Design patterns · mid

Decorator and adapter

An adapter translates a vendor interface into one you own. A decorator wraps the same interface to add retries, timeouts and logging. Together they let you change vendors and add behaviour without touching callers.

The notes

What you must know

  • Own the interface: SmsSender with send(message) returning a SendResult (SENT, RETRYABLE_FAILURE, PERMANENT_FAILURE). VendorAAdapter and VendorBAdapter translate names, parameters and errors into it.
  • Vendor types never leave the adapter (an anti-corruption layer). If the vendor uses callbacks, complete a CompletableFuture or Promise in the callback, or make your interface async.
  • Failover and traffic split go in a separate RoutingSmsSender (a composite plus a strategy: weights, health, circuit breaker), not inside the adapters.
  • Decorators implement the same interface and wrap it: Logging(Retry(Timeout(SdkAdapter))). Callers see one interface and layers are added in wiring.
  • Order matters: a timeout per attempt sits inside the retry. Logging outside sees the final result; inside it sees each attempt.
  • Retry only what is safe: reads and calls with an idempotency key. Never blind-retry a charge. Use exponential backoff with jitter and a cap.
  • Inheritance does not fit: the SDK class may be final, and each combination would need a subclass.
  • Never log card numbers, CVV, full tokens or keys. Mask them.

The red pen

Common traps: mistake → fix

  • Mistake: if (vendor == B) in business code is fine for two vendors

    Fix: it spreads and makes every change risky; use an adapter.

  • Mistake: Map every vendor error to retry

    Fix: permanent failures must stop; keep error kinds.

  • Mistake: Retry loops at each call site are enough

    Fix: they get copied, differ, and hammer a struggling service.

Easy to hard

Questions interviewers ask, easy to hard

  1. We need a second SMS vendor. How do you design it?
  2. What is the difference between adapter and decorator?
  3. How do you add retries and logging around an SDK client you cannot change?
  4. Why does the order of decorators matter?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview