When you travel from India to the UK, your phone charger's plug doesn't fit the wall socket. You don't rebuild the charger or rewire the hotel; you put a small travel adapter in between. Later you might put a phone case on the phone (it still works as a phone, now with extra protection), and at the hotel you simply ask the reception desk for a taxi instead of calling five different companies yourself.
These three everyday ideas — convert an interface, wrap to add features, and one simple front desk for a complex system — are exactly the three structural patterns of this chapter: Adapter, Decorator and Facade.
As we saw in Introduction to Design Patterns, structural patterns are about how classes and objects are composed into larger structures. All three patterns here are built on the principle "favour composition over inheritance": one object holds a reference to another and forwards (delegates) calls to it.
Adapter Pattern
Adapter converts the interface of a class into another interface that clients expect. It lets classes work together that otherwise couldn't because of incompatible interfaces.
The Problem
Your shopping app talks to payment providers through your own interface, PaymentProcessor.pay(orderId, amountInRupees), used in dozens of places. Now the business signs up with a new provider whose SDK looks completely different: a different method name, amounts in paise instead of rupees, extra parameters, and a numeric status code instead of a boolean. You cannot edit the SDK (it's third-party), and you don't want to change dozens of call sites.
The Solution
Write one small class that implements your interface and holds the SDK object. Each call is translated: rename, convert units, convert the result.
Client ──▶ «interface» Target ◀─── implements ─── Adapter ──── has-a ───▶ Adaptee
pay(orderId, rupees) pay(...) { makeTransaction(paise,
convert + delegate currency, ref)
}The four roles: Target (the interface the client wants), Adaptee (the existing class with the wrong interface), Adapter (the translator) and Client (code that uses only the Target).
// Target: the interface our application already uses everywhere
interface PaymentProcessor {
boolean pay(String orderId, double amountInRupees);
}
// Adaptee: a third-party SDK we cannot change (different names, units and return type)
class QuickPaySdk {
public int makeTransaction(long amountInPaise, String currency, String reference) {
System.out.println("QuickPay: charging " + amountInPaise + " paise " + currency + " for " + reference);
return amountInPaise > 0 ? 200 : 400; // HTTP-like status code
}
}
// Adapter: implements the Target, wraps the Adaptee, translates each call
class QuickPayAdapter implements PaymentProcessor {
private final QuickPaySdk sdk;
QuickPayAdapter(QuickPaySdk sdk) {
this.sdk = sdk;
}
@Override
public boolean pay(String orderId, double amountInRupees) {
long paise = Math.round(amountInRupees * 100); // convert units
int status = sdk.makeTransaction(paise, "INR", orderId); // convert the call
return status == 200; // convert the result
}
}
class Checkout {
private final PaymentProcessor processor;
Checkout(PaymentProcessor processor) {
this.processor = processor;
}
void placeOrder(String orderId, double amount) {
boolean ok = processor.pay(orderId, amount);
System.out.println("Order " + orderId + (ok ? " paid" : " FAILED"));
}
}
class AdapterDemo {
public static void main(String[] args) {
Checkout checkout = new Checkout(new QuickPayAdapter(new QuickPaySdk()));
checkout.placeOrder("ORD-101", 499.99);
checkout.placeOrder("ORD-102", 0);
}
}Output:
QuickPay: charging 49999 paise INR for ORD-101
Order ORD-101 paid
QuickPay: charging 0 paise INR for ORD-102
Order ORD-102 FAILEDStep by step for the first order:
Checkoutcallsprocessor.pay("ORD-101", 499.99). It only knows thePaymentProcessorinterface.The adapter converts 499.99 rupees to
Math.round(49999.0)= 49999 paise. (Here499.99 * 100happens to give exactly49999.0, but multiplying adoubleby 100 is not always exact:0.29 * 100gives28.999999999999996, which a plain(long)cast would truncate to 28 paise. Rounding protects us from that.)It calls the SDK's
makeTransaction(49999, "INR", "ORD-101"), which returns 200.It converts 200 into
trueand returns it toCheckout.
Checkout and the SDK never changed. If you switch providers again next year, you write another adapter. This also follows the Open/Closed Principle and Dependency Inversion from the SOLID chapters: high-level code depends on our abstraction, not on a vendor's class.
Object Adapter vs Class Adapter
The version above is an object adapter: the adapter contains the adaptee (composition). The GoF book also describes a class adapter, where the adapter inherits from both the target and the adaptee. That needs multiple inheritance of classes, which Java doesn't allow (unless the target is an interface and you extend the adaptee). C++ supports it directly:
#include <iostream>
#include <string>
class PaymentProcessor { // Target
public:
virtual bool pay(const std::string& orderId, double rupees) = 0;
virtual ~PaymentProcessor() = default;
};
class QuickPaySdk { // Adaptee
public:
int makeTransaction(long long paise, const std::string& currency, const std::string& ref) {
std::cout << "QuickPay: charging " << paise << " paise " << currency << " for " << ref << '\n';
return paise > 0 ? 200 : 400;
}
};
// Class adapter: inherits the interface publicly and the adaptee privately
class QuickPayAdapter : public PaymentProcessor, private QuickPaySdk {
public:
bool pay(const std::string& orderId, double rupees) override {
long long paise = static_cast<long long>(rupees * 100 + 0.5);
return makeTransaction(paise, "INR", orderId) == 200; // inherited method
}
};
int main() {
QuickPayAdapter adapter;
PaymentProcessor& p = adapter;
std::cout << std::boolalpha << p.pay("ORD-201", 250.50) << '\n';
}Output:
QuickPay: charging 25050 paise INR for ORD-201
trueHere private inheritance from QuickPaySdk means "implemented in terms of": the adapter can call makeTransaction() internally, but outside code cannot treat a QuickPayAdapter as a QuickPaySdk.
Object adapter | Class adapter |
|---|---|
Uses composition (has-a adaptee) | Uses inheritance (is-a adaptee) |
Can adapt an adaptee and all its subclasses (pass any of them in) | Fixed to one concrete adaptee class at compile time |
Works in Java, C++, Python, everywhere | Needs to inherit from the adaptee: multiple inheritance in C++/Python, or in Java only |
Cannot override adaptee behaviour easily | Can override some adaptee methods |
In practice, object adapters are far more common.
Adapters in the JDK
InputStreamReaderadapts a byte-basedInputStreaminto a character-basedReader.Arrays.asList(array)lets an array be used through theListinterface (backed by the same array, so its size is fixed).
Decorator Pattern
Decorator attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
The Problem: Subclass Explosion
A food delivery app sells a Veg Biryani for Rs 180. Customers can add raita (+30), a cold drink (+40) and gift packing (+25), in any combination, even two cold drinks. If we used inheritance, we would need classes like BiryaniWithRaita, BiryaniWithRaitaAndDrink, BiryaniWithDrinkAndGiftPack... With 3 add-ons there are 2³ = 8 combinations per dish, and they are fixed at compile time. Add one more add-on and the number doubles.
The Solution: Wrap Objects
A decorator is an object that:
Implements the same interface as the object it decorates (so it can be used anywhere the original can — is-a), and
Holds a reference to an object of that interface (has-a), forwarding calls to it and adding its own behaviour before or after.
Because a decorator is a FoodOrder, it can wrap another decorator. Wrappers stack like Russian dolls:
GiftPack ──wraps──▶ ColdDrink ──wraps──▶ ExtraRaita ──wraps──▶ Biryani
+25 +40 +30 180
cost() call travels inward, results add up on the way back:
GiftPack.cost() = ColdDrink.cost() + 25
= (ExtraRaita.cost() + 40) + 25
= ((Biryani.cost() + 30) + 40) + 25
= 180 + 30 + 40 + 25 = 275// Component
interface FoodOrder {
String description();
double cost();
}
// Concrete component
class Biryani implements FoodOrder {
public String description() { return "Veg Biryani"; }
public double cost() { return 180; }
}
class Dosa implements FoodOrder {
public String description() { return "Masala Dosa"; }
public double cost() { return 90; }
}
// Base decorator: IS-A FoodOrder and HAS-A FoodOrder
abstract class OrderDecorator implements FoodOrder {
protected final FoodOrder inner;
OrderDecorator(FoodOrder inner) {
this.inner = inner;
}
public String description() { return inner.description(); }
public double cost() { return inner.cost(); }
}
class ExtraRaita extends OrderDecorator {
ExtraRaita(FoodOrder inner) { super(inner); }
@Override public String description() { return inner.description() + " + Raita"; }
@Override public double cost() { return inner.cost() + 30; }
}
class ColdDrink extends OrderDecorator {
ColdDrink(FoodOrder inner) { super(inner); }
@Override public String description() { return inner.description() + " + Cold Drink"; }
@Override public double cost() { return inner.cost() + 40; }
}
class GiftPack extends OrderDecorator {
GiftPack(FoodOrder inner) { super(inner); }
@Override public String description() { return inner.description() + " (gift packed)"; }
@Override public double cost() { return inner.cost() + 25; }
}
class DecoratorDemo {
static void print(FoodOrder order) {
System.out.println(order.description() + " = Rs " + order.cost());
}
public static void main(String[] args) {
print(new Biryani());
print(new ExtraRaita(new Biryani()));
print(new GiftPack(new ColdDrink(new ExtraRaita(new Biryani()))));
print(new ColdDrink(new ColdDrink(new Dosa()))); // same decorator twice
}
}Output:
Veg Biryani = Rs 180.0
Veg Biryani + Raita = Rs 210.0
Veg Biryani + Raita + Cold Drink (gift packed) = Rs 275.0
Masala Dosa + Cold Drink + Cold Drink = Rs 170.0With one class per add-on we can build any combination at run time, including the same add-on twice. Adding a new add-on means adding one new class — no existing class changes (Open/Closed Principle). Each decorator also has a single responsibility.
The abstract OrderDecorator base class is optional, but useful: it stores the wrapped object and forwards every method by default, so each concrete decorator overrides only what it changes.
The Real-World Example: Java I/O
The java.io package is the textbook example of Decorator (and contains an Adapter too):
import java.io.*;
import java.nio.charset.StandardCharsets;
class JavaIoDemo {
public static void main(String[] args) throws IOException {
byte[] data = "line one\nline two\n".getBytes(StandardCharsets.UTF_8);
InputStream bytes = new ByteArrayInputStream(data); // byte source
Reader chars = new InputStreamReader(bytes, StandardCharsets.UTF_8); // ADAPTER: bytes -> chars
BufferedReader reader = new BufferedReader(chars); // DECORATOR: adds buffering + readLine()
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Read: " + line);
}
reader.close(); // closing the outer object closes the wrapped ones too
}
}Output:
Read: line one
Read: line twoBufferedReader is a Reader and wraps a Reader, adding buffering and the convenient readLine() method. Similarly, BufferedInputStream, DataInputStream and GZIPInputStream all decorate an InputStream, so you can stack "decompress + buffer + read primitive values" in any order you need. Collections.unmodifiableList(list) and Collections.synchronizedList(list) also wrap a list and change its behaviour while keeping the List interface.
Decorator vs Inheritance
Inheritance | Decorator |
|---|---|
Behaviour added at compile time | Behaviour added at run time |
One subclass per combination (explosion) | One class per feature; combine freely |
Affects every object of the subclass | Affects only the object you wrap |
Simple to read | Many small wrapper objects; harder to debug a deep stack |
Two consequences to remember: a decorated object is not identical to the original (decorated == original is false, and instanceof Biryani fails on the wrapper), and the order of wrapping can matter when decorators do more than add numbers (for example, "encrypt then compress" differs from "compress then encrypt").
Not the Same as Python's @decorator
Python has a syntax feature called decorators (@functools.cache, @staticmethod). It shares the idea of wrapping, but it wraps functions or classes at definition time. The GoF Decorator wraps objects at run time behind a shared interface. Don't use one as the definition of the other in an exam.
Facade Pattern
Facade provides a unified, simpler interface to a set of interfaces in a subsystem, making the subsystem easier to use.
The Problem
Placing an order in an e-commerce system involves several services: reserve stock, charge payment, arrange shipping, send a notification — in the right order, with clean-up if something fails (release the stock if payment is declined). If every client (the website, the mobile app, the admin panel) talks to all four services directly, each one must know the correct sequence and error handling, and all of them break when a service changes.
The Solution
Create one class with a simple method like placeOrder(...) that coordinates the subsystem. Clients call only the facade.
Website Mobile app Admin panel
\ | /
└──────────┼──────────┘
▼
┌─────────────┐
│ OrderFacade │ placeOrder(...)
└──────┬──────┘
┌─────────┬───┴──────┬──────────────┐
▼ ▼ ▼ ▼
Inventory Payment Shipping NotificationService// Subsystem classes (each does one job)
class InventoryService {
boolean reserve(String item, int qty) {
System.out.println("Inventory: reserved " + qty + " x " + item);
return true;
}
void release(String item, int qty) {
System.out.println("Inventory: released " + qty + " x " + item);
}
}
class PaymentService {
boolean charge(String user, double amount) {
boolean ok = amount <= 5000; // pretend the card limit is 5000
System.out.println("Payment: charge Rs " + amount + " to " + user + (ok ? " OK" : " DECLINED"));
return ok;
}
}
class ShippingService {
void ship(String item, String address) {
System.out.println("Shipping: " + item + " to " + address);
}
}
class NotificationService {
void send(String user, String text) {
System.out.println("Notify " + user + ": " + text);
}
}
// Facade: one simple method hides the order of calls and the error handling
class OrderFacade {
private final InventoryService inventory = new InventoryService();
private final PaymentService payment = new PaymentService();
private final ShippingService shipping = new ShippingService();
private final NotificationService notifier = new NotificationService();
public boolean placeOrder(String user, String item, int qty, double price, String address) {
if (!inventory.reserve(item, qty)) {
notifier.send(user, item + " is out of stock");
return false;
}
if (!payment.charge(user, price * qty)) {
inventory.release(item, qty); // undo the reservation
notifier.send(user, "payment failed, order cancelled");
return false;
}
shipping.ship(item, address);
notifier.send(user, "order for " + item + " confirmed");
return true;
}
}
class FacadeDemo {
public static void main(String[] args) {
OrderFacade shop = new OrderFacade();
System.out.println("Result: " + shop.placeOrder("meera", "Notebook", 3, 60, "Chennai"));
System.out.println();
System.out.println("Result: " + shop.placeOrder("arjun", "Laptop", 1, 55000, "Delhi"));
}
}Output:
Inventory: reserved 3 x Notebook
Payment: charge Rs 180.0 to meera OK
Shipping: Notebook to Chennai
Notify meera: order for Notebook confirmed
Result: true
Inventory: reserved 1 x Laptop
Payment: charge Rs 55000.0 to arjun DECLINED
Inventory: released 1 x Laptop
Notify arjun: payment failed, order cancelled
Result: falseThe client wrote one line per order. The facade knew the order of steps and also the compensation step (releasing the reserved laptop when payment failed).
Important points about Facade:
It does not hide the subsystem completely. Advanced clients can still use
PaymentServicedirectly when they need something the facade doesn't offer.It reduces coupling: clients depend on one class instead of four (see Coupling & Cohesion). It is also closely related to the Principle of Least Knowledge (Law of Demeter): talk only to your immediate friends.
It should stay thin: coordinate and delegate. If the facade starts containing all the business logic itself, it turns into a God Object.
Real-world examples: the SLF4J library's name literally means Simple Logging Facade for Java — your code calls one simple logging API, and SLF4J forwards to whichever logging framework is configured. A "service layer" class in a web application is often a facade over repositories and other services.
Adapter vs Decorator vs Facade vs Proxy
All four "wrap" something, which is why they are confused in interviews. The difference is intent:
Pattern | Wraps | Interface seen by client | Purpose |
|---|---|---|---|
Adapter | One object | Different from the wrapped object's | Make an incompatible interface fit |
Decorator | One object | Same as the wrapped object's | Add responsibilities, can be stacked |
Proxy | One object | Same as the wrapped object's | Control access: lazy loading, security checks, remote calls, caching |
Facade | A whole subsystem (many objects) | A new, simpler interface | Make a complex subsystem easy to use |
A one-line memory aid: Adapter changes the interface, Decorator adds behaviour, Proxy controls access, Facade simplifies.
Decorator and Proxy look almost identical in code. The difference: a decorator is usually composed by the client to add features and is meant to be stacked; a proxy usually manages the real object's lifecycle or access and the client often doesn't know it's there.
Common Mistakes
Editing the adaptee instead of writing an adapter. Often you can't (third-party code), and even if you can, you'd break its other users.
Putting business logic in an adapter. An adapter should only translate: names, units, data formats, errors.
A decorator that does not implement the component interface. Then it can't be used in place of the original or wrapped again — it's just a helper class.
Forgetting to delegate in a decorator method, which silently drops the inner object's behaviour.
Relying on object identity or concrete type after decorating (
==orinstanceof Biryanion a wrapper).A facade that grows into a God Object, or one that forbids direct subsystem access entirely.
Calling every wrapper an "adapter". Ask what the wrapper's intent is.
Interview Questions
What is the difference between Adapter and Decorator?
An Adapter changes an object's interface into a different one that clients expect, without adding behaviour. A Decorator keeps the same interface and adds behaviour, and decorators can be stacked on top of each other.
What is the difference between Facade and Adapter?
Adapter wraps one object to make its existing interface match a required interface. Facade defines a new, simpler interface over an entire subsystem of many classes. Adapter is about compatibility; Facade is about simplicity.
Why is Decorator better than inheritance for adding optional features?
With inheritance, every combination of features needs its own subclass (2ⁿ classes for n optional features), fixed at compile time. With decorators you write n classes and combine them freely at run time, even applying the same one twice.
Where is the Decorator pattern used in Java?
In java.io: BufferedReader wraps a Reader, BufferedInputStream/DataInputStream/GZIPInputStream wrap an InputStream. Also Collections.unmodifiableList() and Collections.synchronizedList().
Object adapter or class adapter — which is preferred and why?
Object adapter, usually. It uses composition, works in languages without multiple inheritance, and can adapt the adaptee and any of its subclasses. A class adapter is tied to one concrete adaptee class but can override some of its behaviour.
Does a Facade prevent clients from using the subsystem directly?
No. A facade offers a convenient default path; clients that need more control can still use the subsystem classes. Its goal is simplicity and lower coupling, not enforcement.
Summary
Adapter converts one interface into another so incompatible classes can work together; prefer the object adapter (composition).
InputStreamReaderis a JDK example.Decorator wraps an object behind the same interface to add behaviour at run time; decorators stack and avoid subclass explosion.
java.iois the classic example.Facade gives one simple entry point to a complex subsystem, reducing coupling without forbidding direct access.
Remember: Adapter changes the interface, Decorator adds behaviour, Proxy controls access, Facade simplifies.
Structural patterns arrange objects. In the next chapter, Behavioral Patterns: Observer, Strategy & Command, we look at how objects communicate and share responsibilities.