›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

The Pattern Map

Composite, Bridge and Flyweight, from Shopping Carts to Agent Teams

October 15, 2026 · 12 min read

Design Patterns, C#, Python, Swift, AI, Software Architecture

Part of The Pattern Map: GoF → Cloud → AI. The hub links every pattern in the series.

This is the second structural post. Adapter, Facade and Proxy were the ones you use every week. Composite, Bridge and Flyweight are quieter. People learn them for an interview, nod, and forget them. I think that's a mistake, because all three have come back in AI-era code wearing new clothes:

  • Composite is how an orchestrator agent can treat a team of sub-agents exactly like one agent.
  • Bridge is how one app's features can run on Claude today, a local model tomorrow, and something else next year, without a class for every combination.
  • Flyweight is the idea behind prompt caching: share the heavy, identical part, and send only what's different.

Same format as the rest of the series: the problem, a small example in C# and Python (Swift where it fits naturally, since that's what I write most these days), an honest note on when Python makes the pattern unnecessary, and one line on where you'll meet it now.

Composite

The problem

You have things and groups of things, and groups can contain groups. A cart has products, but it also has bundles, and a bundle can include another bundle. The code that prices the cart shouldn't care which is which. Without Composite, every caller ends up with if (line is Bundle) { loop } else { price }, and the nesting logic leaks everywhere.

Composite says: give the leaf and the group the same interface. The group implements it by delegating to its children. The recursion lives in one place.

C#

var cart = new Bundle("Cart", 0m)
    .Add(new Product("Camera strap", 29.99m))
    .Add(new Bundle("Cleaning kit", 0.10m)        // 10% off the kit
        .Add(new Product("Lens cloth", 4.00m, 3))
        .Add(new Product("Blower", 12.00m)));

Console.WriteLine($"{cart.Name}: {cart.Price():0.00}");   // Cart: 51.59

// The one interface both leaves and groups implement.
public interface ICartLine
{
    string Name { get; }
    decimal Price();
}

// Leaf
public record Product(string Name, decimal UnitPrice, int Quantity = 1) : ICartLine
{
    public decimal Price() => UnitPrice * Quantity;
}

// Composite: holds ICartLines, which may be Products or other Bundles.
public class Bundle(string name, decimal discount) : ICartLine
{
    private readonly List<ICartLine> _lines = [];
    public string Name => name;

    public Bundle Add(ICartLine line) { _lines.Add(line); return this; }

    public decimal Price() => _lines.Sum(l => l.Price()) * (1 - discount);
}

The caller asks the top-level bundle for its price and gets the right answer however deep the nesting goes.

Python

from dataclasses import dataclass, field


@dataclass
class Product:
    name: str
    unit_price: float
    quantity: int = 1

    def price(self) -> float:
        return self.unit_price * self.quantity


@dataclass
class Bundle:
    name: str
    discount: float = 0.0
    lines: list = field(default_factory=list)

    def add(self, line) -> "Bundle":
        self.lines.append(line)
        return self

    def price(self) -> float:
        return sum(line.price() for line in self.lines) * (1 - self.discount)


cart = (
    Bundle("Cart")
    .add(Product("Camera strap", 29.99))
    .add(Bundle("Cleaning kit", discount=0.10)
         .add(Product("Lens cloth", 4.00, quantity=3))
         .add(Product("Blower", 12.00)))
)
print(f"{cart.name}: {cart.price():.2f}")  # Cart: 51.59

(Use Decimal for real money. Floats keep the example short.)

Swift

In Swift, an indirect enum is often the most natural Composite, because the compiler then forces every switch to handle both cases:

import Foundation

indirect enum CartLine {
    case product(name: String, unitPrice: Decimal, quantity: Int = 1)
    case bundle(name: String, discount: Decimal, lines: [CartLine])

    var price: Decimal {
        switch self {
        case let .product(_, unitPrice, quantity):
            return unitPrice * Decimal(quantity)
        case let .bundle(_, discount, lines):
            return lines.reduce(0) { $0 + $1.price } * (1 - discount)
        }
    }
}

let cart = CartLine.bundle(name: "Cart", discount: 0, lines: [
    .product(name: "Camera strap", unitPrice: Decimal(string: "29.99")!),
    .bundle(name: "Cleaning kit", discount: Decimal(string: "0.10")!, lines: [
        .product(name: "Lens cloth", unitPrice: 4, quantity: 3),
        .product(name: "Blower", unitPrice: 12),
    ]),
])
print(cart.price)  // 51.59

And if you write SwiftUI, you use Composite every day. A VStack is a View made of Views, and nothing above it knows or cares.

In Python you often don't need this. Duck typing means Product and Bundle don't share a base class at all; they just both have price(). For pure data, a nested dict or list plus one recursive function is often enough. The idea (one operation that works the same on a leaf and a tree) still matters. The class ceremony is optional.

Where you'll see it now: an orchestrator agent that treats a team of sub-agents like one agent. The OpenAI Agents SDK's agent.as_tool() turns an agent into something another agent can call like any other tool. The shape is Composite:

from typing import Protocol


class Runner(Protocol):
    def run(self, task: str) -> str: ...


class Agent:
    """Leaf: one model call with one job (faked here)."""
    def __init__(self, role: str):
        self.role = role

    def run(self, task: str) -> str:
        return f"[{self.role}] {task}"


class Team:
    """Composite: fans the task out to members, which can be Agents or Teams."""
    def __init__(self, name: str, *members: Runner):
        self.name, self.members = name, members

    def run(self, task: str) -> str:
        return "\n".join(m.run(task) for m in self.members)


review = Team("review",
              Agent("security"),
              Team("style", Agent("naming"), Agent("docs")))
print(review.run("check PR #42"))  # caller can't tell a Team from an Agent

Bridge

The problem

Two things vary independently, and inheritance makes you multiply them. Say an app sends a Reminder and a SecurityAlert, over push and email. With inheritance you write PushReminder, EmailReminder, PushSecurityAlert, EmailSecurityAlert. Add SMS and a third notification type and you have nine classes. That's the class explosion Bridge exists to stop.

Bridge splits the two dimensions into two hierarchies and connects them with a reference: the abstraction (what we're saying) holds an implementation (how it's delivered). Now it's 3 + 3 classes, not 3 × 3.

It looks a lot like Strategy, which I covered in the 2025 patterns post. The difference is intent. Strategy swaps one algorithm inside one class. Bridge is a structural decision up front: two whole class hierarchies that are allowed to grow separately.

C#

IChannel push = new PushChannel(), email = new EmailChannel();

new Reminder(push, "Renew passport", new DateOnly(2027, 1, 15)).Send("bobby");
new SecurityAlert(email, "iPad, Toronto").Send("bobby@example.com");
new Reminder(email, "Renew passport", new DateOnly(2027, 1, 15)).Send("bobby@example.com");

// Implementation side: HOW a message gets delivered.
public interface IChannel
{
    void Deliver(string to, string title, string body);
}

public class PushChannel : IChannel
{
    public void Deliver(string to, string title, string body) =>
        Console.WriteLine($"[push  -> {to}] {title}: {body}");
}

public class EmailChannel : IChannel
{
    public void Deliver(string to, string title, string body) =>
        Console.WriteLine($"[email -> {to}] Subject: {title} | {body}");
}

// Abstraction side: WHAT we're telling the user. Holds the bridge.
public abstract class Notification(IChannel channel)
{
    protected IChannel Channel { get; } = channel;
    public abstract void Send(string to);
}

public class Reminder(IChannel channel, string task, DateOnly due) : Notification(channel)
{
    public override void Send(string to) =>
        Channel.Deliver(to, "Reminder", $"{task} is due {due:MMM d}");
}

public class SecurityAlert(IChannel channel, string device) : Notification(channel)
{
    public override void Send(string to) =>
        Channel.Deliver(to, "New sign-in", $"Signed in from {device}. Not you? Reset your password.");
}

Adding SMS is one new IChannel. Adding a "trial ending" notification is one new Notification. Neither touches the other side.

Python

class PushChannel:
    def deliver(self, to, title, body):
        print(f"[push  -> {to}] {title}: {body}")


class EmailChannel:
    def deliver(self, to, title, body):
        print(f"[email -> {to}] Subject: {title} | {body}")


class Reminder:
    def __init__(self, channel, task, due):
        self.channel, self.task, self.due = channel, task, due

    def send(self, to):
        self.channel.deliver(to, "Reminder", f"{self.task} is due {self.due}")


Reminder(PushChannel(), "Renew passport", "Jan 15").send("bobby")
Reminder(EmailChannel(), "Renew passport", "Jan 15").send("bobby@example.com")

In Python you often don't need this. The abstract base classes disappear. You don't need an IChannel; anything with a deliver method works. And if the implementation side is really just one operation, pass a function instead of an object. At that point Bridge is "a class that takes a callable in its constructor", and most Python developers wouldn't call it a pattern at all.

Where you'll see it now: your app's AI features on one side, model providers on the other. This is the Bridge I actually care about as an app builder. My features (summarize a thread, draft release notes) shouldn't know whether they run on a hosted API or a local model:

from typing import Callable

# Implementation side: any function with this shape is a "model".
Complete = Callable[[str], str]


def claude_api(prompt: str) -> str:      # stand-in for a hosted API call
    return f"(hosted) {prompt[:40]}..."


def local_model(prompt: str) -> str:     # stand-in for a local model
    return f"(local) {prompt[:40]}..."


# Abstraction side: features of MY app, written once against Complete.
class Summarizer:
    def __init__(self, complete: Complete):
        self.complete = complete

    def summarize(self, text: str) -> str:
        return self.complete(f"Summarize in one line: {text}")


class ReleaseNotesWriter:
    def __init__(self, complete: Complete):
        self.complete = complete

    def write(self, commits: list[str]) -> str:
        return self.complete("Write release notes for: " + "; ".join(commits))


# 2 features x 2 models = 4 combinations, zero extra classes.
print(Summarizer(claude_api).summarize("A long support thread about sync bugs"))
print(Summarizer(local_model).summarize("A long support thread about sync bugs"))
print(ReleaseNotesWriter(local_model).write(["fix sync", "dark mode"]))

In .NET this is now built in. Microsoft.Extensions.AI defines an IChatClient interface that provider libraries implement, so your code is written against the abstraction and the provider is a registration detail. Microsoft's docs pitch it for exactly this: portability across models and services, and easier testing.

Flyweight

The problem

You need a huge number of small objects, and most of each object is identical to thousands of others. Think of a photo library app holding 10,000 frames. Every frame shot on the same lens carries the same lens-correction profile, maybe a 16 KB distortion table. Store a copy per frame and that's around 160 MB of identical data. Store it once and share it, and it's 16 KB per lens.

Flyweight names the split:

  • Intrinsic state: the heavy, immutable part that's the same across many objects. Shared.
  • Extrinsic state: the small part that's unique per object (file name, ISO). Kept per object, or passed in.

A factory hands out the shared instance so nobody creates a duplicate by accident.

C#

var lenses = new[] { "RF 70-200mm F4", "RF 16-28mm F2.8" };
var frames = new List<Frame>();
for (var i = 0; i < 10_000; i++)
{
    var profile = LensProfiles.Get("EOS R6 Mark III", lenses[i % 2]);
    frames.Add(new Frame($"IMG_{i:0000}.CR3", Iso: 100 * (i % 64 + 1), profile));
}

Console.WriteLine($"{frames.Count} frames, {LensProfiles.Count} profiles in memory");
Console.WriteLine(ReferenceEquals(frames[0].Profile, frames[2].Profile)); // True

// Intrinsic state: heavy, immutable, identical for every frame shot on this lens.
public sealed class LensProfile(string camera, string lens)
{
    public string Camera { get; } = camera;
    public string Lens { get; } = lens;
    public float[] DistortionTable { get; } = new float[4096]; // ~16 KB, loaded once
}

// Flyweight factory: hands out the shared instance.
public static class LensProfiles
{
    private static readonly Dictionary<(string, string), LensProfile> Cache = [];

    public static LensProfile Get(string camera, string lens)
    {
        if (!Cache.TryGetValue((camera, lens), out var profile))
            Cache[(camera, lens)] = profile = new LensProfile(camera, lens);
        return profile;
    }

    public static int Count => Cache.Count;
}

// Extrinsic state: small, per-frame. Points at the shared flyweight.
public readonly record struct Frame(string FileName, int Iso, LensProfile Profile);

Output: 10000 frames, 2 profiles in memory. In a real app the factory would need to be thread-safe (ConcurrentDictionary), and the shared object must be immutable. If one frame could edit "its" profile, it would silently edit everyone's.

You already use a flyweight in .NET: string.Intern keeps one copy of each distinct string.

Python

from dataclasses import dataclass
from functools import cache


@dataclass(frozen=True)
class LensProfile:                      # intrinsic: heavy, immutable, shared
    camera: str
    lens: str
    distortion: tuple


@cache                                  # the whole flyweight factory
def lens_profile(camera: str, lens: str) -> LensProfile:
    return LensProfile(camera, lens, distortion=tuple([0.0] * 4096))


@dataclass(slots=True)
class Frame:                            # extrinsic: small, per frame
    file_name: str
    iso: int
    profile: LensProfile


lenses = ["RF 70-200mm F4", "RF 16-28mm F2.8"]
frames = [
    Frame(f"IMG_{i:04}.CR3", 100 * (i % 64 + 1),
          lens_profile("EOS R6 Mark III", lenses[i % 2]))
    for i in range(10_000)
]
print(len(frames), "frames,", len({id(f.profile) for f in frames}), "profiles")
print(frames[0].profile is frames[2].profile)  # True

In Python you often don't need this. functools.cache on a constructor function is the flyweight factory, in one line. frozen=True gives you the immutability, and slots=True keeps the per-frame objects small. CPython already does this for you in places: small integers are shared, and sys.intern does for strings what string.Intern does in .NET.

Where you'll see it now: prompt caching. An agent sends the same system prompt and tool definitions on every turn, and only the new messages differ. That's intrinsic and extrinsic state again. Anthropic's prompt caching caches the prompt prefix (tools, then system, then messages) up to a marked point. Their docs say cache reads are billed at a tenth of the normal input price or less depending on the model, with a default five-minute lifetime. Put the shared, heavy part first and keep it byte-identical, and every request after the first pays for it at the cheap rate. The design rule is pure Flyweight: never let per-request data leak into the shared part.

The map so far

PatternOld clothesNew clothes
CompositeCart bundles, UI view trees, file systemsAgent teams; agents as tools
BridgeNotification × channelApp features × model providers (IChatClient)
FlyweightGlyphs, map tiles, string.InternPrompt caching; shared prompt prefixes

Next in the series (Jan 5): the first behavioral post, Command, Chain of Responsibility, Mediator and Template Method. That's where tool calls and guardrails come in.

Further reading

  • The series hub, with every pattern on one page
  • OpenAI Agents SDK docs on tools, including agents as tools
  • Microsoft Learn: Microsoft.Extensions.AI libraries, the IChatClient abstraction
  • Anthropic docs on prompt caching
  • Python docs for functools.cache
  • Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, Helm, Johnson, Vlissides), the original catalogue
← Previous

Meta's Two-Track Bet, and a Roadster That Hops

Next →

Changing Live Systems: Anti-Corruption Layer, Expand and Contract, Feature Flags

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.