THN Interview Prep

Flyweight (Structural)

Intent / problem it solves

Share intrinsic (immutable) state across many fine-grained objects to reduce memory. Extrinsic state stays outside the flyweight and is passed in at use time.

When to use / when NOT

Use when you instantiate huge numbers of similar objects (icons, characters in an editor, game tiles).

Avoid when object counts are modest or sharing complicates thread safety; measure before optimizing.

Structure

Flyweight factory caches instances keyed by intrinsic state; clients supply extrinsic context.

Loading diagram…

Go example

package main

import "fmt"

type Glyph struct {
	codePoint rune
}

type GlyphFactory struct {
	pool map[rune]*Glyph
}

func NewGlyphFactory() *GlyphFactory {
	return &GlyphFactory{pool: map[rune]*Glyph{}}
}

func (factory *GlyphFactory) Fetch(codePoint rune) *Glyph {
	if glyph, ok := factory.pool[codePoint]; ok {
		return glyph
	}
	glyph := &Glyph{codePoint: codePoint}
	factory.pool[codePoint] = glyph
	return glyph
}

func main() {
	factory := NewGlyphFactory()
	first := factory.Fetch('A')
	second := factory.Fetch('A')
	fmt.Println(first == second)
}

JavaScript example

class IconFlyweight {
  constructor(name, svgPath) {
    this.name = name;
    this.svgPath = svgPath;
  }
}

class IconFactory {
  constructor() {
    this.cache = new Map();
  }

  getIcon(name) {
    if (!this.cache.has(name)) {
      this.cache.set(
        name,
        new IconFlyweight(name, `/icons/${name}.svg`),
      );
    }
    return this.cache.get(name);
  }
}

const factory = new IconFactory();
const left = factory.getIcon('home');
const right = factory.getIcon('home');
console.log(left === right);

Interview phrase

“Flyweight caches immutable glyphs or icons so thousands of document nodes share one heavy bitmap definition; position and color stay extrinsic.”

Link from LLD for rich text, map tiles, or emoji rendering caches in LLD case studies.

Last updated on

Spotted something unclear or wrong on this page?

On this page