Structural Patterns
Adapter, Decorator, Facade, Proxy, Composite, Bridge and Flyweight — how to compose objects into larger structures, with code, real-world examples (Java I/O streams, middleware, ORMs, API gateways) and how to tell similar patterns apart.
Overview
| Pattern | Intent | Real-world examples |
|---|---|---|
| Adapter | make incompatible interfaces work together | wrapping third-party SDKs, legacy systems |
| Decorator | add responsibilities dynamically, same interface | Java I/O streams, middleware, @retry |
| Facade | simple interface to a complex subsystem | CheckoutService, SDK clients |
| Proxy | control access to an object | lazy loading in ORMs, RPC stubs, caching proxies |
| Composite | treat trees of objects uniformly | file systems, UI trees, org charts |
| Bridge | vary abstraction and implementation independently | JDBC, logging facades |
| Flyweight | share common state across many objects | glyphs, game assets, interning |
Adapter
Java
// Our domain interface
interface PaymentGateway { PaymentResult charge(String customer, long amountMinor); }
// Third-party SDK we can't change
class LegacyPayClient {
LegacyResponse makePayment(double amountRupees, String custRef, String currency) { /* ... */ return null; }
}
// Adapter translates calls and data
class LegacyPayAdapter implements PaymentGateway {
private final LegacyPayClient client;
LegacyPayAdapter(LegacyPayClient client) { this.client = client; }
public PaymentResult charge(String customer, long amountMinor) {
LegacyResponse r = client.makePayment(amountMinor / 100.0, customer, "INR");
return r.code() == 0 ? PaymentResult.ok(r.txnId()) : PaymentResult.failed(r.message());
}
}
Decorator
interface DataSource { byte[] read(String key); void write(String key, byte[] data); }
class S3DataSource implements DataSource { /* real I/O */
public byte[] read(String k) { return new byte[0]; } public void write(String k, byte[] d) {} }
abstract class DataSourceDecorator implements DataSource {
protected final DataSource inner;
DataSourceDecorator(DataSource inner) { this.inner = inner; }
public byte[] read(String k) { return inner.read(k); }
public void write(String k, byte[] d) { inner.write(k, d); }
}
class CachingDataSource extends DataSourceDecorator {
private final Map<String, byte[]> cache = new ConcurrentHashMap<>();
CachingDataSource(DataSource inner) { super(inner); }
@Override public byte[] read(String k) { return cache.computeIfAbsent(k, inner::read); }
@Override public void write(String k, byte[] d) { inner.write(k, d); cache.put(k, d); }
}
class CompressingDataSource extends DataSourceDecorator {
CompressingDataSource(DataSource inner) { super(inner); }
@Override public byte[] read(String k) { return Gzip.decompress(inner.read(k)); }
@Override public void write(String k, byte[] d) { inner.write(k, Gzip.compress(d)); }
}
// compose at runtime
DataSource ds = new CachingDataSource(new CompressingDataSource(new S3DataSource()));
import functools, time, random
def retry(times=3, base=0.1):
def deco(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(times):
try:
return fn(*args, **kwargs)
except ConnectionError:
if attempt == times - 1:
raise
time.sleep(random.uniform(0, base * 2 ** attempt))
return wrapper
return deco
@retry(times=5)
def fetch_rates():
...
Facade
Java
public class CheckoutFacade {
private final InventoryService inventory;
private final PaymentService payments;
private final ShippingService shipping;
private final NotificationService notifications;
public CheckoutFacade(InventoryService i, PaymentService p, ShippingService s, NotificationService n) {
this.inventory = i; this.payments = p; this.shipping = s; this.notifications = n;
}
public OrderConfirmation placeOrder(Cart cart, PaymentDetails pay, Address addr) {
Reservation res = inventory.reserve(cart.items());
try {
Receipt receipt = payments.charge(pay, cart.total());
Shipment shipment = shipping.schedule(cart.items(), addr);
notifications.orderPlaced(cart.customerId(), shipment);
return new OrderConfirmation(receipt, shipment);
} catch (RuntimeException e) {
inventory.release(res); // facade hides the compensation logic too
throw e;
}
}
}
Proxy
Java
interface Image { void display(); }
class HighResImage implements Image {
private final byte[] pixels;
HighResImage(String path) { this.pixels = Files.readAllBytesUnchecked(path); } // expensive
public void display() { /* draw */ }
}
class LazyImageProxy implements Image { // virtual proxy: load on first use
private final String path;
private HighResImage real;
LazyImageProxy(String path) { this.path = path; }
public void display() {
if (real == null) real = new HighResImage(path);
real.display();
}
}
Proxy types: virtual (lazy loading — Hibernate lazy associations), remote (gRPC stubs make a remote service look local), protection (check permissions before delegating), caching, logging/metrics, smart reference (reference counting).
Composite
Java
interface FsNode { String name(); long size(); }
record FileNode(String name, long size) implements FsNode {}
final class FolderNode implements FsNode {
private final String name;
private final List<FsNode> children = new ArrayList<>();
FolderNode(String name) { this.name = name; }
FolderNode add(FsNode n) { children.add(n); return this; }
public String name() { return name; }
public long size() { return children.stream().mapToLong(FsNode::size).sum(); } // recursive
}
Bridge
Java
interface Sender { void deliver(String to, String text); } // implementation side
class EmailSender implements Sender { public void deliver(String to, String t) {} }
class SmsSender implements Sender { public void deliver(String to, String t) {} }
abstract class Notification { // abstraction side
protected final Sender sender;
Notification(Sender sender) { this.sender = sender; }
abstract void notify(User u);
}
class SecurityAlert extends Notification {
SecurityAlert(Sender s) { super(s); }
void notify(User u) { sender.deliver(u.contact(), "New login detected on your account"); }
}
class WeeklyDigest extends Notification {
WeeklyDigest(Sender s) { super(s); }
void notify(User u) { sender.deliver(u.contact(), digestFor(u)); }
private String digestFor(User u) { return "..."; }
}
// 2 notifications × 2 senders without 4 subclasses
Flyweight
Java
record TreeType(String species, Mesh mesh, Texture texture) {} // intrinsic, shared, immutable
final class TreeTypeFactory {
private static final Map<String, TreeType> CACHE = new ConcurrentHashMap<>();
static TreeType get(String species) {
return CACHE.computeIfAbsent(species, s -> new TreeType(s, Mesh.load(s), Texture.load(s)));
}
}
record Tree(float x, float y, TreeType type) {} // extrinsic: position
// 1,000,000 trees, only a handful of TreeType objects in memory
Telling them apart
| If you need to… | Use |
|---|---|
| make an existing class fit an interface you own | Adapter |
| add features without changing the interface | Decorator |
| control/defer access to an expensive or remote object | Proxy |
| simplify a messy subsystem for callers | Facade |
| treat a tree of objects as one | Composite |
| combine two independent dimensions of variation | Bridge |
| save memory across huge numbers of similar objects | Flyweight |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.