Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 7 min read

Structural Design Patterns: Adapter, Decorator and Facade Explained

The shipping company you integrated three years ago still returns fields like price_cents and dest_zip, your new code speaks priceCents, and somebody has just asked for logging, caching and a retry on every carrier call.

Structural Design Patterns: Adapter, Decorator and Facade Explained

The shipping company you integrated three years ago still returns fields like price_cents and dest_zip, your new code speaks priceCents, and somebody has just asked for logging, caching and a retry on every carrier call. Structural design patterns are the answer to this kind of problem. They do not decide how objects are created or what they do. They decide how objects and classes fit together, so that old code, new code and extra behaviour can meet without rewriting any of them.

Key takeaways

  • The 1994 Gang of Four book describes 23 patterns, and seven of them are structural: Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy.

  • Adapter, Decorator and Facade all wrap another object, but they do three different jobs: change the interface, add behaviour, and simplify a large subsystem.

  • Decorators stack because every layer has the same interface as the thing it wraps, so one line decides the order of logging, caching and retries.

  • A Facade makes callers simpler; it does not make the subsystem behind it safer or transactional.

  • If you can change the original class, change it. Wrappers are for code you cannot or should not touch.

Working definition
A structural design pattern is a reusable way of composing classes and objects into larger structures while keeping the parts independent of each other.

The problem: code that almost fits

In part 2 of this series we moved the decision about which object to build into one place. Once the objects exist, a different problem shows up: they have to work together, and they were not designed to. A vendor SDK uses another naming style. A feature needs the same extra step around five different calls. A checkout screen has to talk to stock, payments, shipping and email in the right order.

The Gang of Four book, Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, Helm, Johnson and Vlissides, 1994), describes 23 patterns. Its structural group is defined as patterns that concern class and object composition. The seven are shown below; this guide covers the three you will meet most often in application code.

We will use one small online shop throughout. It needs shipping quotes, and every example below builds on the same interface:

interface Parcel { weightKg: number; destZip: string; }
interface Quote  { price: number; etaDays: number; }

// What our application wants to talk to
interface RateProvider { quote(parcel: Parcel): Promise; }

Adapter: make an old interface fit

An adapter wraps an existing class and presents it through the interface a client expects. Wikipedia’s article on the pattern puts the goal plainly: it lets the interface of an existing class be used as another interface, often to make existing classes work with others without modifying their source code.

Here the carrier’s SDK is old and cannot change. It takes weights and zip codes in its own field names and returns prices in cents:

// Third-party code we cannot edit
class LegacyCarrierClient {
  getRate(req: { weight_kg: number; dest_zip: string })
    : Promise { /* ... */ }
}

class CarrierAdapter implements RateProvider {
  constructor(private legacy: LegacyCarrierClient) {}

  async quote(p: Parcel): Promise {
    const r = await this.legacy.getRate({ weight_kg: p.weightKg, dest_zip: p.destZip });
    return { price: r.price_cents / 100, etaDays: r.eta_days };
  }
}

All the translation lives in one class: field names, units and nothing else. The rest of the application only knows RateProvider. When the carrier ships version 2 of its SDK, one file changes. If you want to check how a name like price_cents maps to priceCents while you write a mapper, our case converter does it in a click.

Screenshot of the AIGS case converter turning price_cents into priceCents
Figure 2 β€” Our own case converter turning the carrier’s price_cents into priceCents, the kind of renaming an adapter does for every field. Screenshot: ai-gs.net, December 2026.

Tip
Keep adapters boring. If an adapter starts making business decisions, such as choosing the cheapest carrier, that logic belongs in a domain class that uses the adapter, not inside it.

Decorator: add behaviour without subclassing

A decorator wraps an object that has the same interface and adds behaviour before or after delegating to it. Wikipedia describes it as a way to add behaviour to an individual object dynamically without affecting other instances of the same class, and notes that it is a flexible alternative to subclassing. Without it, you would need a new subclass for every combination: a logging carrier, a caching carrier, a logging-and-caching carrier, and so on.

class CachingRates implements RateProvider {
  private cache = new Map();
  constructor(private inner: RateProvider) {}

  async quote(p: Parcel): Promise {
    const key = p.weightKg + ':' + p.destZip;
    const hit = this.cache.get(key);
    if (hit) return hit;
    const q = await this.inner.quote(p);
    this.cache.set(key, q);
    return q;
  }
}

class LoggingRates implements RateProvider {
  constructor(private inner: RateProvider, private log = console.log) {}

  async quote(p: Parcel): Promise {
    const t = Date.now();
    const q = await this.inner.quote(p);
    this.log('quote', p.destZip, (Date.now() - t) + 'ms');
    return q;
  }
}

// One line decides the order of the layers
const rates: RateProvider =
  new LoggingRates(new CachingRates(new CarrierAdapter(new LegacyCarrierClient())));

Notice that the adapter and both decorators implement RateProvider, so they plug into each other freely. Moving logging inside the cache, to log only real carrier calls, is a one-line change where the stack is built. Wikipedia points out that the I/O stream classes in both Java and the .NET Framework use this pattern, which is why you routinely wrap one stream in another.

A wrapper that keeps the interface adds behaviour. A wrapper that changes the interface adapts. Knowing which one you are writing is half the design.

Caution
Cache and retry only calls that are safe to repeat. A shipping quote is a read, so both are fine. A payment charge is not, and a retry decorator around it can charge twice unless the call is idempotent. We cover that later in this series.

Facade: one door to a busy subsystem

A facade gives a large or messy subsystem one simple entry point. Wikipedia notes that developers often use it when a system is complex or hard to understand because it has many interdependent classes, or when its source code is unavailable. The checkout screen in our shop should not know the order in which stock, payment, shipping and email are called:

class CheckoutFacade {
  constructor(
    private stock: Inventory,
    private pay: PaymentGateway,
    private rates: RateProvider,
    private mail: Mailer,
  ) {}

  async placeOrder(cart: Cart): Promise {
    await this.stock.reserve(cart.items);
    const shipping = await this.rates.quote(cart.parcel);
    const receipt = await this.pay.charge(cart.total + shipping.price);
    await this.mail.sendReceipt(cart.email, receipt);
    return receipt;
  }
}

The UI now calls placeOrder(cart) and nothing else. The facade is also the natural place to test the whole flow with fakes. Two honest limits apply. First, a facade does not make the steps atomic: if the payment fails after the stock was reserved, somebody still has to release the stock. Second, it should not become a place where every new rule is added, or it turns into a large class that breaks the rules from part 1.

β€œAdapter and Decorator are the same thing because both wrap an object.”

Both wrap, but the contract is different. An adapter changes the interface so that incompatible code can work together. A decorator keeps the interface and adds behaviour around it.

β€œPython’s @decorator syntax is the Decorator pattern.”

They are different things. The Python Wiki, quoted on Wikipedia, says the pattern from the Design Patterns book should not be confused with Python decorators, which are a language feature for modifying a function or class. You can use the language feature to build the pattern, but they are not the same idea.

Telling the three apart

  • Two pieces of code that should fit but have different interfaces: Adapter.

  • One interface that needs extra behaviour, in combinations you cannot predict: Decorator.

  • A subsystem with many parts and callers who only want the common path: Facade.

  • The abstraction and its implementation should change independently: Bridge, covered in the diagram above but rarer in everyday code.

  • A tree of objects treated as one, shared state, or controlled access: Composite, Flyweight and Proxy.

As with the creational patterns, the honest test is whether you can name the change the pattern makes cheap. If you do not own the class and cannot name a second variant, a direct call is still fine. If you do own it and the interface is simply wrong, fix the interface.

A checklist you can run today

  • List every third-party SDK your code calls directly. For each one, ask whether the rest of the code would survive its replacement. If not, put an adapter in front of it.

  • Search for repeated before-and-after code around calls: timing, logging, caching, permission checks. Each is a decorator candidate.

  • Find the screen or handler that calls four or more services in sequence. Move that sequence into a facade and test it with fakes.

  • Check that every wrapper implements the same interface as the thing it wraps, or, for an adapter, the interface your application owns.

  • Write down, for each facade, what happens when step three fails after steps one and two succeeded.

If a system has grown many of these seams and nobody has a map of them, the AIGS systems analysis service starts with exactly that kind of dependency map.

Further reading
The structural pattern list and the book’s publication details are on Wikipedia’s Design Patterns article. For each pattern in this guide, see Adapter, Decorator and Facade.

Part 3 of 14 β€” Engineering Foundations series

Previous: Creational Design Patterns: Factory, Builder and the Singleton Trap. Next: behavioral design patterns, Strategy, Observer and Command, which deal with how objects communicate and share responsibility.

Browse the rest of the series on the AIGS blog, or see how we apply it in client work on the services page.

Originally published at ai-gs.net.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.