# Bridge and Flyweight in Brief — Design Patterns

Source: https://www.skillbyai.com/en/design-patterns/s-bridge-flyweight

> Separate dimensions; share repeated state.

## Two less common structural patterns

**Bridge** separates an abstraction from its implementation so the two can vary independently. If you have notification *types* (alert, reminder, digest) and *channels* (email, SMS, push), subclassing every combination gives types x channels classes; a Bridge gives each notification a reference to a channel instead, so you add either dimension without touching the other. It is composition over inheritance applied to two axes. **Flyweight** saves memory when you have very many similar objects by sharing their common, immutable (**intrinsic**) state and passing the varying (**extrinsic**) state in from outside: for example, millions of map markers sharing a handful of icon objects, or characters in a text editor sharing glyph data. Flyweight is a performance optimisation; use it only when profiling shows memory is the problem.

## Bridge and Flyweight sketches

Two independent dimensions, and a shared icon cache.

```typescript
// Bridge: notification kinds x delivery channels
interface Channel { deliver(to: string, title: string, body: string): Promise<void>; }

abstract class Notification {
  constructor(protected channel: Channel) {}
  abstract send(to: string): Promise<void>;
}
class PasswordReset extends Notification {
  send(to: string) { return this.channel.deliver(to, 'Reset your password', resetBody()); }
}
class WeeklyDigest extends Notification {
  send(to: string) { return this.channel.deliver(to, 'Your week', digestBody()); }
}
new PasswordReset(new SmsChannel()).send('+15550100');

// Flyweight: share heavy, immutable icon data across many markers
const iconCache = new Map<string, Icon>();
function getIcon(kind: string): Icon {
  let icon = iconCache.get(kind);
  if (!icon) { icon = loadIcon(kind); iconCache.set(kind, icon); }
  return icon;
}
// each marker stores only position (extrinsic) + a shared icon (intrinsic)
const markers = points.map((p) => ({ lat: p.lat, lng: p.lng, icon: getIcon(p.kind) }));
```

## You may already use these

String interning and small-integer caches in language runtimes are flyweights, and a driver interface behind a database library is a bridge, even if nobody named them.

**Quiz:** What problem does Bridge address?

- [x] A class explosion when two dimensions of variation are combined through inheritance
- [ ] Too many network calls
- [ ] Undoing user actions
- [ ] Iterating over a tree

*Answer:* A class explosion when two dimensions of variation are combined through inheritance. Bridge lets each dimension vary independently.
