| name | structural |
| description | Structural design patterns from the Gang of Four — Adapter, Bridge, Composite, Decorator, Facade, Flyweight, and Proxy. Patterns that compose classes and objects into larger structures while keeping those structures flexible and efficient.
USE FOR: adapting interfaces, composing objects into trees, adding behavior dynamically, simplifying complex subsystems, sharing objects efficiently, controlling access via proxies
DO NOT USE FOR: object creation (use creational), communication patterns (use behavioral)
|
| license | MIT |
| metadata | {"displayName":"Structural Patterns","author":"Tyler-R-Kendrick"} |
| compatibility | claude, copilot, cursor |
| references | [{"title":"Refactoring.Guru — Structural Design Patterns","url":"https://refactoring.guru/design-patterns/structural-patterns"},{"title":"Structural Pattern — Wikipedia","url":"https://en.wikipedia.org/wiki/Structural_pattern"}] |
Structural Design Patterns
Overview
Structural patterns are concerned with how classes and objects are composed to form larger structures. Structural class patterns use inheritance to compose interfaces or implementations. Structural object patterns describe ways to compose objects to realize new functionality — the added flexibility of object composition comes from the ability to change the composition at runtime.
1. Adapter
Intent
Convert the interface of a class into another interface that clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces.
Structure
┌──────────────┐ ┌──────────────────┐
│ Client │───────▶│ Target │
└──────────────┘ │ (interface) │
├──────────────────┤
│ + request() │
└──────┬───────────┘
│ implements
▼
┌──────────────┐ ┌──────────────────┐
│ Adaptee │◀───────│ Adapter │
├──────────────┤ wraps ├──────────────────┤
│ + specificReq()│ │ + request() │
└──────────────┘ └──────────────────┘
Participants
- Target — defines the domain-specific interface that Client uses
- Client — collaborates with objects conforming to the Target interface
- Adaptee — defines an existing interface that needs adapting
- Adapter — adapts the interface of Adaptee to the Target interface
When to Use
- You want to use an existing class, but its interface does not match the one you need
- You want to create a reusable class that cooperates with unrelated or unforeseen classes
- You need to integrate a third-party library without coupling your code to its API
TypeScript Example
class LegacyAnalytics {
sendXML(xml: string): void {
console.log(`[Legacy] Sending XML: ${xml}`);
}
}
interface Analytics {
track(event: string, data: Record<string, unknown>): void;
}
class AnalyticsAdapter implements Analytics {
constructor(private legacy: LegacyAnalytics) {}
track(event: string, data: Record<string, unknown>): void {
const xml = `<event name="${event}">${
Object.entries(data)
.map(([k, v]) => `<${k}>${v}</${k}>`)
.join("")
}</event>`;
this.legacy.(xml);
}
}
: = ( ());
analytics.(, { : , : });
2. Bridge
Intent
Decouple an abstraction from its implementation so that the two can vary independently.
Structure
┌────────────────────┐ ┌─────────────────────┐
│ Abstraction │────────▶│ Implementor │
├────────────────────┤ has-a │ (interface) │
│ + operation() │ ├─────────────────────┤
└──────┬─────────────┘ │ + operationImpl() │
│ extends └──────┬──────────────┘
▼ │ implements
┌────────────────────┐ ┌───────┴──────────────┐
│ RefinedAbstraction │ │ │
├────────────────────┤ ┌─────────────┐ ┌─────────────┐
│ + operation() │ │ ConcreteImplA│ │ ConcreteImplB│
└────────────────────┘ └─────────────┘ └─────────────┘
Participants
- Abstraction — defines the abstraction's interface; maintains a reference to Implementor
- RefinedAbstraction — extends the interface defined by Abstraction
- Implementor — defines the interface for implementation classes
- ConcreteImplementor — implements the Implementor interface
When to Use
- You want to avoid a permanent binding between an abstraction and its implementation
- Both the abstraction and its implementation should be extensible via subclassing
- You have a class explosion from combining two independent dimensions of variation (e.g., Shape x Renderer, Notification x Channel)
TypeScript Example
interface NotificationChannel {
send(title: string, body: string): void;
}
class EmailChannel implements NotificationChannel {
send(title: string, body: string): void {
console.log(`[Email] Subject: ${title} | Body: ${body}`);
}
}
class SlackChannel implements NotificationChannel {
send(title: string, body: string): void {
console.log(`[Slack] *${title}*: ${body}`);
}
}
class SMSChannel implements NotificationChannel {
send(title: string, body: string): void {
console.log(`[SMS] : `);
}
}
{
() {}
(: ): ;
}
{
(: ): {
..(, );
}
}
{
(: ): {
..(, message);
}
}
urgentEmail = ( ());
urgentEmail.();
infoSlack = ( ());
infoSlack.();
3. Composite
Intent
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Structure
┌──────────────────┐
│ Component │◀─────────────────────┐
│ (interface) │ │
├──────────────────┤ │
│ + operation() │ │
└──────┬───────────┘ │ children
│ implements │
├──────────────────┐ │
▼ ▼ │
┌──────────────┐ ┌──────────────┐ │
│ Leaf │ │ Composite │──────┘
├──────────────┤ ├──────────────┤
│ + operation() │ │ + operation() │
└──────────────┘ │ + add() │
│ + remove() │
│ + getChild() │
└──────────────┘
Participants
- Component — declares the interface for objects in the composition
- Leaf — represents leaf objects in the composition (no children)
- Composite — defines behavior for components with children; stores child components
When to Use
- You want to represent part-whole hierarchies of objects
- You want clients to treat individual objects and compositions uniformly
- File systems, org charts, UI component trees, menu structures
TypeScript Example
interface FileSystemNode {
name: string;
getSize(): number;
print(indent?: string): string;
}
class File implements FileSystemNode {
constructor(public name: string, private size: number) {}
getSize(): number { return this.size; }
print(indent = ""): string {
return `${indent}📄 ${this.name} (${this.size} bytes)`;
}
}
class Directory implements FileSystemNode {
private children: FileSystemNode[] = [];
constructor(public name: string) {}
add(node: ): {
..(node);
;
}
(: ): {
. = ..( c !== node);
}
(): {
..( sum + child.(), );
}
(indent = ): {
lines = [];
( child .) {
lines.(child.(indent + ));
}
lines.();
}
}
root = ()
.( (, ))
.( ()
.( (, ))
.( (, )))
.( (, ));
.(root.());
.();
4. Decorator
Intent
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Structure
┌──────────────────┐
│ Component │◀──────────────────────┐
│ (interface) │ │
├──────────────────┤ │
│ + operation() │ │ wraps
└──────┬───────────┘ │
│ implements │
├──────────────────┐ │
▼ ▼ │
┌────────────────┐ ┌─────────────────┐ │
│ ConcreteComp. │ │ Decorator │────┘
├────────────────┤ ├─────────────────┤
│ + operation() │ │ + operation() │
└────────────────┘ └──────┬──────────┘
│ extends
┌──────┴──────────┐
▼ ▼
┌────────────┐ ┌────────────┐
│ DecoratorA │ │ DecoratorB │
├────────────┤ ├────────────┤
│ + operation()│ │ + operation()│
└────────────┘ └────────────┘
Participants
- Component — defines the interface for objects that can have responsibilities added
- ConcreteComponent — the object to which additional responsibilities are attached
- Decorator — maintains a reference to a Component and conforms to Component's interface
- ConcreteDecorator — adds responsibilities to the component
When to Use
- You want to add responsibilities to individual objects dynamically, without affecting other objects
- You want to add responsibilities that can be withdrawn
- Extension by subclassing is impractical (e.g., the number of combinations explodes)
TypeScript Example
interface DataSource {
write(data: string): string;
read(): string;
}
class FileDataSource implements DataSource {
private content = "";
write(data: string): string {
this.content = data;
return `Written: ${data}`;
}
read(): string {
return this.content;
}
}
abstract class DataSourceDecorator implements DataSource {
constructor(protected wrappee: DataSource) {}
write(data: string): string {
return this.wrappee.write(data);
}
read(): string {
return ..();
}
}
{
(: ): {
encrypted = .(data).();
.(encrypted);
}
(): {
data = .();
.(data, ).();
}
}
{
(: ): {
compressed = ;
.(compressed);
}
(): {
data = .();
data.(, );
}
}
{
(: ): {
.();
.(data);
}
(): {
.();
.();
}
}
: = ();
source = (source);
source = (source);
source = (source);
source.();
.(source.());
5. Facade
Intent
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Structure
┌────────────────┐
│ Client │
└──────┬─────────┘
│ uses
▼
┌─────────────────────────┐
│ Facade │
├─────────────────────────┤
│ + simpleOperation() │
└──┬──────┬──────┬────────┘
│ │ │
▼ ▼ ▼
┌──────┐┌──────┐┌──────┐
│Sub-A ││Sub-B ││Sub-C │
│ ││ ││ │
└──────┘└──────┘└──────┘
Subsystem classes
Participants
- Facade — provides simple methods that delegate to subsystem classes; knows which subsystem classes are responsible for a request
- Subsystem classes — implement subsystem functionality; handle work assigned by the Facade; have no knowledge of the Facade
When to Use
- You want to provide a simple interface to a complex subsystem
- There are many dependencies between clients and implementation classes
- You want to layer your subsystems — use a Facade for each level
TypeScript Example
class VideoDecoder {
decode(file: string): string {
return `decoded-frames(${file})`;
}
}
class AudioDecoder {
decode(file: string): string {
return `decoded-audio(${file})`;
}
}
class SubtitleParser {
parse(file: string): string[] {
return [`00:01 Hello`, `00:05 World`];
}
}
class VideoRenderer {
render(frames: string, audio: string, subs: string[]): string {
return `Rendering: ${frames} + ${audio} with ${subs.length} subtitles`;
}
}
class MediaPlayerFacade {
private videoDecoder = new VideoDecoder();
private audioDecoder = new AudioDecoder();
subtitleParser = ();
renderer = ();
(: , ?: ): {
frames = ..(videoFile);
audio = ..(videoFile);
subs = subtitleFile
? ..(subtitleFile)
: [];
..(frames, audio, subs);
}
}
player = ();
.(player.(, ));
6. Flyweight
Intent
Use sharing to support large numbers of fine-grained objects efficiently.
Structure
┌─────────────────┐ ┌────────────────────┐
│ FlyweightFactory │──────▶│ Flyweight │
├─────────────────┤pool │ (interface) │
│ + getFlyweight() │ ├────────────────────┤
└─────────────────┘ │ + operation(extSt) │
└──────┬─────────────┘
│ implements
┌──────┴─────────────┐
▼ ▼
┌──────────────┐ ┌──────────────────┐
│ ConcreteFW │ │ UnsharedConcreteFW│
│ (shared) │ │ (not shared) │
├──────────────┤ ├──────────────────┤
│ intrinsicState│ │ allState │
└──────────────┘ └──────────────────┘
Participants
- Flyweight — declares an interface through which flyweights can receive and act on extrinsic state
- ConcreteFlyweight — stores intrinsic (shared) state; must be shareable
- FlyweightFactory — creates and manages flyweight objects; ensures sharing
- Client — maintains extrinsic state; passes it to flyweight operations
When to Use
- An application uses a large number of objects
- Storage costs are high because of the sheer quantity of objects
- Most object state can be made extrinsic (passed in at operation time)
- Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed
TypeScript Example
class TreeType {
constructor(
public readonly name: string,
public readonly color: string,
public readonly texture: string
) {}
render(x: number, y: number): string {
return `[${this.name}] color=${this.color} at (${x},${y})`;
}
}
class TreeTypeFactory {
private static types = new Map<string, TreeType>();
static getType(name: string, color: string, texture: string): TreeType {
const key = `${name}-${color}-${texture}`;
if (!..(key)) {
..(key, (name, color, texture));
.();
}
..(key)!;
}
(): {
..;
}
}
{
: ;
() {
. = .(name, color, texture);
}
(): {
..(., .);
}
}
: [] = [];
( i = ; i < ; i++) {
forest.( (
.() * ,
.() * ,
i % === ? : i % === ? : ,
i % === ? : ,
));
}
.();
7. Proxy
Intent
Provide a surrogate or placeholder for another object to control access to it.
Structure
┌──────────────────┐
│ Subject │◀──────────────────────┐
│ (interface) │ │
├──────────────────┤ │
│ + request() │ │ delegates to
└──────┬───────────┘ │
│ implements │
├──────────────────┐ │
▼ ▼ │
┌────────────────┐ ┌─────────────────┐ │
│ RealSubject │ │ Proxy │────┘
├────────────────┤ ├─────────────────┤
│ + request() │ │ - realSubject │
└────────────────┘ │ + request() │
└─────────────────┘
Participants
- Subject — defines the common interface for RealSubject and Proxy
- RealSubject — defines the real object that the proxy represents
- Proxy — maintains a reference to the RealSubject; controls access to it
Proxy Variants
| Variant | Purpose |
|---|
| Virtual Proxy | Lazy-loads expensive objects on first access |
| Protection Proxy | Controls access based on permissions |
| Caching Proxy | Caches results of expensive operations |
| Logging Proxy | Logs all operations for debugging/auditing |
| Remote Proxy | Represents an object in a different address space |
When to Use
- You need lazy initialization (virtual proxy)
- You need access control (protection proxy)
- You need caching of expensive operations (caching proxy)
- You want to log or audit access to an object (logging proxy)
TypeScript Example
interface WeatherService {
getForecast(city: string): string;
}
class RealWeatherService implements WeatherService {
getForecast(city: string): string {
console.log(` [API] Fetching weather for ${city}...`);
return `${city}: 72F, Sunny`;
}
}
class WeatherServiceProxy implements WeatherService {
private cache = new Map<string, { data: string; expiry: number }>();
private readonly TTL = 60_000;
constructor(private service: RealWeatherService) {}
getForecast(city: string): string {
cached = ..(city);
(cached && cached. > .()) {
.();
cached.;
}
.();
data = ..(city);
..(city, { data, : .() + . });
data;
}
}
{
() {}
(: ): {
(. !== && . !== ) {
();
}
..(city);
}
}
: = ();
service = (service );
service = (service, );
.(service.());
.(service.());
Comparison Table
| Pattern | Key Mechanism | Problem It Solves | Key Distinction |
|---|
| Adapter | Wraps one interface into another | Incompatible interfaces | Changes the interface of an existing object |
| Bridge | Separates abstraction from implementation | Two independent dimensions of variation | Designed up-front to let abstraction and implementation vary |
| Composite | Tree of uniform components | Part-whole hierarchies | Lets clients treat single objects and compositions uniformly |
| Decorator | Wraps an object, adds behavior | Adding responsibilities dynamically | Adds behavior without changing the interface |
| Facade | Simplified interface to a subsystem | Complex subsystem with many classes | Provides a new, simpler interface |
| Flyweight | Shares intrinsic state | Too many fine-grained objects in memory | Reduces object count by sharing common parts |
| Proxy | Controls access to an object | Controlled access, caching, lazy loading | Same interface as the real object but controls access |
Decision Guide
Do you need to compose or wrap objects?
│
├─ Make incompatible interfaces work together?
│ └──▶ Adapter
│
├─ Vary abstraction and implementation independently?
│ └──▶ Bridge
│
├─ Represent tree / part-whole hierarchies?
│ └──▶ Composite
│
├─ Add or remove behavior dynamically?
│ └──▶ Decorator
│
├─ Simplify a complex subsystem interface?
│ └──▶ Facade
│
├─ Reduce memory for many similar objects?
│ └──▶ Flyweight
│
└─ Control access, cache, or lazy-load?
└──▶ Proxy
Commonly Confused Pairs
Adapter vs Facade
- Adapter makes an existing interface conform to another existing interface (1:1 wrapping)
- Facade creates a new simplified interface over multiple subsystem classes (1:many simplification)
Decorator vs Proxy
- Decorator adds new behavior (the client knows it is decorating)
- Proxy controls access to existing behavior (the client treats it identically to the real object)
Composite vs Decorator
- Both use recursive composition, but Composite aggregates children (one-to-many) while Decorator wraps a single component (one-to-one) to add behavior