📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Adapter, Decorator, Proxy and Facade all wrap something. How do you tell them apart? Compare their intent, interface and typical .NET examples, and explain why the distinction matters in a real codebase.

A comparison of the four wrapper patterns: Adapter (converts an interface), Decorator (same interface, adds behaviour), Proxy (same interface, controls access and lifecycle), Facade (new simpler interface over many classes), with .NET examples, a decision guide, and why mislabelling leads to misplaced logic such as duplicate retries.

Mid-Level Theory Intermediate adapter decorator design-patterns facade proxy structural-patterns

🎯 Key points

  • Adapter: different interface, wraps one adaptee, converts it to what the client expects (StripePaymentGateway, StreamReader)
  • Decorator: same interface, wraps one object, adds behaviour and can stack (caching repository, GZipStream, DelegatingHandler)
  • Proxy: same interface, wraps one subject, controls access, creation or location (EF Core lazy-loading proxy, gRPC client, authorisation wrapper)
  • Facade: new, simpler interface over several classes or a subsystem (File.ReadAllTextAsync, a PlaceOrder handler)
  • Quick test: does the interface change? (Adapter/Facade) Is it one object or many? (Adapter vs Facade) Does it add features or control access? (Decorator vs Proxy)
  • Decorator and Proxy have identical structure; the difference is intent. Proxies commonly create or locate their subject (lazy, remote), decorators are usually handed one, but neither rule is absolute
  • The distinction tells you where responsibilities belong: retry in an adapter plus a resilience handler multiplies attempts (idempotency keys stop duplicate effects, not the extra load); business rules in a facade create a god service
  • Name classes by what they do in the domain, and use the pattern name in reviews and ADRs to agree on responsibilities

⏱ 30-second answer

All four wrap something, but for different reasons:

Pattern Interface Wraps Purpose
Adapter Different from the wrapped type One object Convert it to what the client expects
Decorator Same One object Add behaviour; stackable
Proxy Same One object Control access: lazy creation, remoting, permissions
Facade New, simpler Many classes Simplify a subsystem

The quick test is three questions. Does the interface change? Is it one object or many? Does it add features or control access?

The distinction matters because it tells you where a responsibility belongs. Put retries in an adapter that already sits behind a resilience handler, and every failure is retried twice over.

🗣 Full answer (senior)

How I would answer this in an interview

"They all wrap something, so I tell them apart by why the wrapper exists, and two quick questions get you most of the way. First, does the interface change? An Adapter exposes a different interface from the thing it wraps: it converts Stripe's SDK into my IPaymentGateway, or a byte Stream into a TextReader. A Facade exposes a new, simpler interface, but over many classes rather than one: File.ReadAllTextAsync over streams and encodings, or a PlaceOrder handler over inventory, payments and shipping. Decorator and Proxy keep the same interface as what they wrap.

Second, for the same-interface pair: does it add behaviour or control access? A Decorator adds a feature such as caching, metrics or compression, and you can stack several. A Proxy controls access to its subject. It might create the subject lazily, like EF Core's lazy-loading proxies, or it might stand in for something remote, like a gRPC client, or check permissions first. Structurally they're identical. The difference is intent, and the fact that a proxy often owns its subject's lifecycle, while a decorator is handed an object.

Why it matters: the pattern name tells the team what belongs in the class. The mistake I see is responsibilities ending up in the wrong wrapper. For example, at [company] someone added retries inside a payment adapter while the typed HttpClient already had AddStandardResilienceHandler. Each failure was retried up to [three times three] attempts, and because the requests weren't idempotent, [some customers were charged twice]. Retry is a decorator-style concern that belongs in exactly one layer. The adapter should only translate. Agreeing on which wrapper you're writing is how you agree on what it's allowed to do."


Side by side

Adapter Decorator Proxy Facade
Interface vs wrapped Different Same Same New, simpler
Wraps One object One object One object A subsystem (many)
Intent Convert Add behaviour Control access/lifecycle Simplify
Stackable Rarely Yes Sometimes No
Creates the wrapped object No No Often Sometimes
.NET examples StreamReader, TaskCompletionSource, Serilog provider GZipStream, BufferedStream, DelegatingHandler EF Core lazy proxies, gRPC stubs, Lazy<T> File.ReadAllTextAsync, HttpClient, DbContext
App example StripePaymentGateway : IPaymentGateway CachedProductRepository AuthorisedDocumentStore PlaceOrderHandler

Decision guide

Question Answer → pattern
Interface differs from the wrapped type, one object? Adapter
New simplified interface over several classes? Facade
Same interface, adds a feature? Decorator
Same interface, controls when/whether/where the real object is used? Proxy

What belongs where

Concern Natural home
Unit/type/error translation Adapter
Retry, caching, metrics, logging Decorator (or DelegatingHandler), in one layer only
Authorisation, lazy creation, remoting Proxy
Use-case orchestration Facade / application service
Business rules Domain model, never the wrapper

Production example

A team found retries in three places for one outgoing payment call: inside the adapter, in a custom DelegatingHandler, and in AddStandardResilienceHandler. One transient 503 produced up to 27 attempts. After an incident review, the adapter was reduced to translation, the custom handler was removed, and idempotency keys were added. Duplicate charges dropped to zero and provider rate-limit errors fell by about 80%.

🔍 What the interviewer is checking

Checks conceptual precision across the structural patterns and whether the candidate uses that precision to put responsibilities in the right place.

Green flags

  • Distinguishes by interface change, number of wrapped objects and intent.
  • Notes Decorator and Proxy share structure and differ by intent.
  • Gives correct .NET examples for each.
  • Connects the distinction to real bugs (duplicate retries, misplaced rules).

Red flags

  • Treats the names as interchangeable.
  • Classifies purely by structure.
  • No sense of why the distinction matters.

📚 Learn in depth

1. The shared skeleton

Client ──▶ Wrapper ──▶ Wrapped

Every wrapper pattern is composition plus delegation. That's why intent is the only reliable way to tell them apart, and why the GoF book describes each pattern by its intent first.

2. Where they blur

  • Decorator vs Proxy: a caching wrapper could be called a "caching proxy" or a "caching decorator". Convention: if it's about adding a feature to an object you're given, call it a decorator; if it's about controlling access to a subject it creates or locates, a proxy.
  • Adapter vs Facade: an adapter over a large SDK starts to look like a facade. Convention: if its job is making the SDK fit your interface, it's an adapter; if its job is making a subsystem easier to use, it's a facade.
  • Adapter + Decorator: real code often stacks them, e.g. RetryingPaymentGateway (decorator) → StripePaymentGateway (adapter) → Stripe SDK. Keeping them separate keeps each one single-purpose.

3. Composition in a typical outgoing call

CheckoutService
   → IPaymentGateway       (MetricsDecorator: adds timing)
   → IPaymentGateway       (StripePaymentGateway: Adapter, translates)
   → Stripe SDK → HttpClient (Facade over the handler chain)
   → DelegatingHandler     (logging handler: Decorator)
   → ResilienceHandler     (retry, breaker, timeouts: Decorator)
   → SocketsHttpHandler    (real transport)

Each layer has one job. Retries happen in one place (the resilience handler); the adapter doesn't retry.

4. Why names matter in reviews

When a reviewer says "this is supposed to be an adapter, why does it make pricing decisions?", the pattern name gives a shared standard. ADRs that record "payment providers are adapters; resilience lives in the HTTP pipeline" prevent drift.

Try it yourself

  1. Classify ten wrapper classes in your codebase using the decision guide; note any that do two jobs.
  2. Trace one outgoing HTTP call and list every layer and its pattern.
  3. Search for retry logic (for (int attempt, Polly pipelines, AddStandardResilienceHandler) and check that each call path retries in exactly one layer.
  4. Write the "what belongs where" table as an ADR for your team.

💻 Code

The four patterns side by side around one domain:

namespace Wrappers;

public interface IPaymentGateway
{
    Task<PaymentResult> ChargeAsync(Guid orderId, decimal amountAud, CancellationToken ct);
}

// ADAPTER: different interface (vendor SDK) -> our interface; translation only, no retries
public sealed class StripePaymentGateway(Stripe.PaymentIntentService intents) : IPaymentGateway
{
    public async Task<PaymentResult> ChargeAsync(Guid orderId, decimal amountAud, CancellationToken ct)
    {
        var pi = await intents.CreateAsync(
            new Stripe.PaymentIntentCreateOptions { Amount = (long)(amountAud * 100m), Currency = "aud", Confirm = true },
            new Stripe.RequestOptions { IdempotencyKey = orderId.ToString() }, cancellationToken: ct);
        return new PaymentResult(pi.Status == "succeeded", pi.Id, pi.Status);
    }
}

// DECORATOR: same interface, adds a feature (metrics), given its inner object
public sealed class MeteredPaymentGateway(IPaymentGateway inner, PaymentMetrics metrics) : IPaymentGateway
{
    public async Task<PaymentResult> ChargeAsync(Guid orderId, decimal amountAud, CancellationToken ct)
    {
        using var _ = metrics.MeasureCharge();
        return await inner.ChargeAsync(orderId, amountAud, ct);
    }
}

// PROXY: same interface, controls access (and creates the real gateway lazily)
public sealed class RestrictedPaymentGateway(Lazy<IPaymentGateway> real, ICurrentUser user) : IPaymentGateway
{
    public Task<PaymentResult> ChargeAsync(Guid orderId, decimal amountAud, CancellationToken ct) =>
        user.HasPermission("payments.charge")
            ? real.Value.ChargeAsync(orderId, amountAud, ct)
            : throw new UnauthorizedAccessException("Missing payments.charge permission.");
}

// FACADE: new, simpler interface over several subsystems
public sealed class CheckoutFacade(IInventory inventory, IPaymentGateway payments, IShipping shipping)
{
    public async Task<string> PlaceOrderAsync(Cart cart, CancellationToken ct)
    {
        await inventory.ReserveAsync(cart.Lines, ct);
        await payments.ChargeAsync(cart.OrderId, cart.Total, ct);
        return await shipping.BookAsync(cart.OrderId, ct);
    }
}
// Program.cs: retries live in ONE place, the HTTP pipeline, not in the adapter
// builder.Services.AddHttpClient("stripe").AddStandardResilienceHandler();
// builder.Services.AddScoped<StripePaymentGateway>();
// builder.Services.AddScoped<IPaymentGateway>(sp => new MeteredPaymentGateway(
//     sp.GetRequiredService<StripePaymentGateway>(), sp.GetRequiredService<PaymentMetrics>()));

⚠ Common mistakes

  • Mistake: Deciding by structure ("it wraps an object, so it's a decorator"). Why it is wrong: All four have similar structure; intent is what differs. Instead: Ask whether the interface changes, how many objects are wrapped, and what the purpose is.
  • Mistake: Adding retries inside an adapter that already sits behind a resilience handler. Why it is wrong: Attempts multiply, providers rate-limit you, and non-idempotent calls can duplicate charges. Instead: One retry layer, plus idempotency keys.
  • Mistake: Letting an adapter or facade make business decisions. Why it is wrong: Rules become vendor-specific or end up in a god service. Instead: Wrappers translate, add cross-cutting behaviour or orchestrate; rules live in the domain.
  • Mistake: Calling a class "Proxy" when it just forwards everything. Why it is wrong: It's a do-nothing layer (a poltergeist). Instead: Remove it, or give it a real purpose.
  • Mistake: Combining two wrapper roles in one class (adapter that also caches and checks permissions). Why it is wrong: It's hard to test, reorder or remove one concern. Instead: One role per class, composed in DI.
  • Mistake: Naming classes after patterns (PaymentAdapterDecoratorProxy). Why it is wrong: Names describe mechanics, not purpose. Instead: Domain names (StripePaymentGateway, CachedProductRepository), with the pattern in docs or reviews.

🏛 Senior insight: trade-offs

In practice the four wrappers stack around every external call, and the senior skill is keeping one responsibility per layer. Most production bugs I've seen with wrappers aren't about misnaming; they're about a responsibility living in two layers (double retries, double logging) or in the wrong one (business rules in a facade, caching outside authorisation).

Question in review Red flag
Does this adapter do anything except translate? Retries, caching, rules inside it
Is this decorator's position in the chain deliberate? Cache outside auth or tenant filtering
Does this proxy hide expensive work? Lazy loading in a loop, remote call without timeout
Is this facade only orchestrating? Validation and rules, 10+ dependencies

I write the layering for outgoing calls into an ADR (adapter translates; resilience in the HTTP pipeline; metrics as a decorator) and check new integrations against it.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate uses the payment SDK adapter as an example Why: Checks Adapter in depth: translation, units and errors
    How to answer

    Adapter converts the interface of an existing class into the interface your code expects, without changing either side. It's a translator.

    • An object adapter wraps the adaptee by composition. This is the normal C# form.
    • A class adapter inherits the adaptee and implements the target. C# allows only one base class, so it's rare.

    For a payment SDK, I define IPaymentGateway in my domain's terms. A StripePaymentGateway adapter then turns it into SDK calls, translating types and units (decimal AUD to cents), statuses and vendor exceptions into domain results. That keeps vendor types out of the codebase, lets tests use a fake, and confines a provider change to one class.

    The trade-off is an extra layer. Keep it thin: an adapter translates, and business rules don't belong in it.

  2. When: Candidate says Proxy controls access or lazy creation Why: Checks Proxy kinds and hidden costs like lazy loading
    How to answer

    A Proxy has the same interface as the real object and controls access to it:

    • A virtual proxy delays creating something expensive: Lazy<T>, and EF Core lazy-loading proxies that load a navigation on first access.
    • A remote proxy makes a network call look like a local call: gRPC stubs, Refit or Kiota clients.
    • A protection proxy checks permissions before delegating.

    .NET builds proxies at run time. EF Core generates subclasses through Castle, so navigations must be virtual. DispatchProxy creates interface proxies through Invoke(MethodInfo, args), but it uses Reflection.Emit and so isn't AOT-friendly. Castle DynamicProxy powers Moq and NSubstitute.

    The trade-off is invisible behaviour. Code that looks like a property read can run a query (N+1), throw after the context is disposed, or make a network call.

🛠 Real-world problems: how you handle them

Retries in three layers turned one 503 into 27 payment attempts
Situation
A checkout on .NET [10] calling a payment provider through a vendor SDK, [~5,000] payments an hour. The payment adapter had its own retry loop, a custom `DelegatingHandler` retried 5xx, and the typed client had `AddStandardResilienceHandler`.
Signals
During a provider brownout, the provider returned 429 rate-limit errors to us; [a handful of] customers reported double charges; provider logs showed up to [27] requests for one order within [~20 seconds].
Investigation
Traced one order in Application Insights: nested spans showed the adapter's loop (3 attempts) each going through the custom handler (3) each through the resilience handler (3). Requests had no idempotency key, so the provider treated retries after a timeout as new charges.
Resolution
Immediate: disabled the adapter's retry loop and the custom handler via configuration; refunded duplicate charges. Real fix: adapter reduced to translation; one retry layer (the standard resilience handler) with jittered backoff; idempotency key = order ID on every charge.
Prevention
ADR: 'adapters translate, resilience lives in the HTTP pipeline'; a test asserting a single retry layer by counting attempts against a fake handler; an architecture rule flagging retry loops in adapter classes.

How to tell it (STAR)

**S:** At [company] a payment provider brownout turned into double charges for [some] customers. **T:** I led the incident review and had to stop it recurring. **A:** One order's trace showed up to [27] attempts: our adapter retried, a custom handler retried, and the standard resilience handler retried, all nested. And there was no idempotency key, so timed-out requests became new charges. We switched off two of the layers and refunded customers, then reduced the adapter to pure translation, kept one retry layer, added idempotency keys, and wrote the layering into an ADR. **R:** Duplicate charges went to [zero], provider rate-limit errors fell by [~80%], and the attempt-count test has blocked one regression since.

↩ Usually asked after

More in Structural Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me