The Flyweight Pattern is used to minimize memory usage by sharing as much data as possible with other similar objects. It is the secret behind high-performance gaming engines and text editors that can handle millions of characters with zero lag.
We use a Flyweight Factory. When you ask for an object, the factory checks if it already has one in memory. If yes, it returns the existing instance. If no, it creates a new one and stores it for the next person.
public class TreeFactory
{
private static Dictionary<string, TreeType> _types = new();
public static TreeType GetTreeType(string name, string color)
{
// If we already have a 'Green Oak', reuse the object!
if (!_types.ContainsKey(name))
_types[name] = new TreeType(name, color);
return _types[name];
}
}
Q: "How does the .NET 'String Intern Pool' implement the Flyweight pattern?"
Architect Answer: ".NET maintains a hidden table (the Intern Pool) for all literal strings. If you have 10,000 variables all set to the string 'Error', the CLR doesn't create 10,000 objects. It creates ONE 'Error' object (the Flyweight) and points all 10,000 variables to that same memory address. This saves significant RAM and makes string comparison (`==`) much faster. This is Flyweight in action at the runtime level."