SOLID & Design Patterns Interview Question #54

What is the Flyweight Pattern?

Advanced Patterns, CQRS & Domain-Driven Design Fundamentals Mid-Level Intermediate

Quick Interview Answer

The Flyweight Pattern reduces memory usage by sharing common immutable state among many logical objects instead of duplicating that state in every instance. Instance-specific state is kept separately.

Detailed Explanation

The Flyweight Pattern reduces memory usage by sharing common immutable state among many logical objects instead of duplicating that state in every instance. Instance-specific state is kept separately.

It is most useful when an application creates a very large number of similar objects and profiling shows duplicated state is a meaningful memory cost. It adds complexity and should not be introduced without a real need.

Code Example

public sealed record TextStyle(
    string FontFamily,
    int FontSize,
    bool Bold);

// Many text runs can share the same
// immutable TextStyle instance.