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 Core → Enterprise → Cloud & 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.
What happened?
- PinStyle is intrinsic/shared; store id and coordinates are extrinsic.
- Factory caches styles.
- ReferenceEquals is true for the shared style.
Practice next
- Create two pins sharing a style; confirm ReferenceEquals.
- Request a red style and see a second cache entry.
- Keep PinStyle immutable.
- Print Cache.Count after several Get calls.
- 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.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!