{
    "slug": "flyweight_pattern",
    "term": "Flyweight Pattern",
    "category": "quality",
    "difficulty": "advanced",
    "short": "A structural pattern that shares common state between many objects rather than storing it in each instance — dramatically reducing memory for large numbers of similar objects.",
    "long": "Flyweight separates intrinsic state (shared, immutable — stored in the flyweight) from extrinsic state (unique, context-dependent — passed by the client). A flyweight factory ensures each unique intrinsic state is only instantiated once. Classic example: a text editor storing character formatting — rather than one object per character with its font stored on each, share font objects across all characters using the same font. PHP applications: caching expensive configuration objects, connection pools, icon/resource caches.",
    "aliases": [
        "flyweight",
        "object pool",
        "shared state"
    ],
    "tags": [
        "patterns",
        "memory",
        "performance",
        "oop"
    ],
    "misconception": "Flyweight is only relevant for extremely large systems — any PHP application rendering thousands of repeated components (table rows, list items with shared formatters) benefits from flyweight.",
    "why_it_matters": "Creating one object per rendered row in a 10,000-row table with shared formatters uses 10,000× more memory than flyweight — the pattern is the difference between workable and out-of-memory.",
    "common_mistakes": [
        "Storing extrinsic (context-specific) state in the flyweight — defeats the purpose by making it non-shareable.",
        "Flyweight objects that are mutable — shared objects must be immutable; mutation in one context corrupts all others.",
        "Not using a factory — without a factory, client code may create duplicates instead of sharing.",
        "Premature flyweight optimisation — measure memory usage first; flyweight adds complexity only justified by real memory pressure."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "object_pooling",
        "memoization",
        "factory_pattern",
        "memory_leak"
    ],
    "prerequisites": [
        "memory_management",
        "factory_pattern",
        "immutability"
    ],
    "refs": [
        "https://refactoring.guru/design-patterns/flyweight"
    ],
    "bad_code": "// One object per row — wasteful if formatter is identical:\nclass TableRow {\n    private NumberFormatter $formatter;\n    public function __construct(private array $data) {\n        $this->formatter = new NumberFormatter('en-US', NumberFormatter::CURRENCY);\n        // New formatter for every row — 10,000 rows = 10,000 identical formatters\n    }\n}",
    "good_code": "// Flyweight — shared formatter:\nclass FormatterFactory {\n    private static array $cache = [];\n    public static function get(string $locale, int $style): NumberFormatter {\n        $key = $locale . ':' . $style;\n        return self::$cache[$key] ??= new NumberFormatter($locale, $style);\n    }\n}\n\nclass TableRow {\n    public function __construct(private array $data) {}\n    public function formatAmount(): string {\n        // Shared — created once, reused by all rows:\n        return FormatterFactory::get('en-US', NumberFormatter::CURRENCY)\n            ->formatCurrency($this->data['amount'], 'USD');\n    }\n}",
    "quick_fix": "Share identical immutable objects from a factory instead of creating new ones — PHP's interned strings already do this; apply flyweight when you have thousands of objects with shared state",
    "severity": "low",
    "effort": "high",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/flyweight_pattern",
        "html_url": "https://codeclaritylab.com/glossary/flyweight_pattern",
        "json_url": "https://codeclaritylab.com/glossary/flyweight_pattern.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Flyweight Pattern](https://codeclaritylab.com/glossary/flyweight_pattern) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/flyweight_pattern"
            }
        }
    }
}