Tutorials Design Patterns in C#

Flyweight Pattern — Complete Guide

Flyweight Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.

On this page

Design Patterns in C# · Lesson 11 of 69

Flyweight Pattern

GoF CoreEnterpriseCloud & Craft

GoF Core · 1 — Create & structure · ~6 min · Module 2: Structural Design Patterns

What is this?

Flyweight shares common immutable state across many objects to save memory — extrinsic state passes in per call.

Why should you care?

ShopNest map pins for thousands of stores reuse the same icon/style objects instead of copying them.

See it live — copy this example

Paste into a C# console or class library project and run dotnet run.

public sealed class PinStyle
{
    public string Icon { get; }
    public string Color { get; }
    public PinStyle(string icon, string color) { Icon = icon; Color = color; }
}
public static class PinStyleFactory
{
    private static readonly Dictionary<string, PinStyle> Cache = new();
    public static PinStyle Get(string icon, string color)
    {
        var key = icon + ":" + color;
        if (!Cache.TryGetValue(key, out var style))
            Cache[key] = style = new PinStyle(icon, color);
        return style;
    }
}
public readonly record struct StorePin(string StoreId, double Lat, double Lng, PinStyle Style);

var style = PinStyleFactory.Get("shop", "blue");
var pins = new[] { new StorePin("s1", 18.5, 73.8, style), new StorePin("s2", 18.6, 73.9, style) };
Console.WriteLine(ReferenceEquals(pins[0].Style, pins[1].Style));

Run Example »

Edit the code below and click Run to see the result in Toolliyo’s live editor.

Code
Result

What happened?

  • PinStyle is intrinsic/shared; store id and coordinates are extrinsic.
  • Factory caches styles.
  • ReferenceEquals is true for the shared style.

Practice next

  1. Create two pins sharing a style; confirm ReferenceEquals.
  2. Request a red style and see a second cache entry.
  3. Keep PinStyle immutable.
  4. Print Cache.Count after several Get calls.
  5. Add a size field to PinStyle.

Remember

Share immutable intrinsic state. Pass extrinsic per use. Cache carefully.

ShopNest store-map pins

Map renders thousands of pins with few styles.

Outcome: Memory stays flat as store count grows.

Interview prep for this lesson

Practice these questions aloud after reading—each links to a full structured answer.

Mid PDF Detailed
Flyweight Objects (Character):?
Short answer: The Character class holds the intrinsic state (the character symbol), which is shared across all instances. This makes it an ideal candidate for the Flyweight Pattern because multiple characters (e.g., 'H',…
Mid PDF Detailed
Flyweight (Character):?
Short answer: This class represents the Flyweight object. It contains the intrinsic state that is shared across multiple instances (the character symbol, in this case), and it provides a Display method to show the charac…
Mid PDF Detailed
Abstract Factory (LoggerFactory):?
Short answer: The LoggerFactory class defines a factory method CreateLogger that returns an ILogger object. This is a generic interface for creating various logger types without specifying the concrete class directly. Re…
Mid PDF Detailed
Redo Functionality:?
Short answer: You can extend the system by adding redo functionality. After an undo operation, you could store the undone command in a separate stack and allow users to redo the previous undo operation. Real-world exampl…
Mid PDF Detailed
Abstract Expression (IExpression):?
Short answer: The IExpression interface declares an Interpret method, which is the core of the interpreter pattern. This method is used to interpret and evaluate expressions. public interface IExpression Example code { i…
Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns in C#
Course syllabus

Design Patterns in C# Tutorial

Module 1: Creational Design Patterns
Module 2: Structural Design Patterns
Module 3: Behavioral Design Patterns
Module 4: Enterprise Design Patterns
Module 5: Modern Enterprise Patterns
Module 6: Microservices & Cloud Patterns
Module 7: ASP.NET Core Architecture Patterns
Module 8: Interview & System Design
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details