Flyweight Pattern in C# – Real-Time Example (Memory Optimization)
What is Flyweight Pattern?
The Flyweight Pattern is a structural design pattern that reduces memory usage by sharing common objects instead of creating duplicate objects.
It is mainly used when applications create a large number of similar objects.
Why Use Flyweight Pattern?
- Reduce memory consumption
- Improve performance
- Reuse shared objects
- Avoid duplicate object creation
Real-Time Scenario
Examples:
- Thousands of icons/images in UI
- Characters in text editor
- Game objects (trees, bullets)
- Cache systems
👉 Instead of creating many identical objects, reuse existing ones.
Real-Time Example – Icon System
Suppose a UI application displays:
- Many file icons
- Same image repeated multiple times
Without Flyweight:
1000 objects → high memory usage
With Flyweight:
1 shared icon object reused
Real-Time Example – Document Editor
Step 1: Flyweight Object
public class Character
{
private readonly char _symbol;
public Character(char symbol)
{
_symbol = symbol;
}
public void Display(int position)
{
Console.WriteLine(
$"Character: {_symbol}, Position: {position}"
);
}
}
Step 2: Flyweight Factory
public class CharacterFactory
{
private readonly Dictionary<char, Character> _characters = new();
public Character GetCharacter(char symbol)
{
if (!_characters.ContainsKey(symbol))
{
_characters[symbol] = new Character(symbol);
}
return _characters[symbol];
}
}
Usage Example
var factory = new CharacterFactory();
var charA1 = factory.GetCharacter('A');
var charA2 = factory.GetCharacter('A');
charA1.Display(1);
charA2.Display(2);
Console.WriteLine(
ReferenceEquals(charA1, charA2)
);
Output
Character: A, Position: 1 Character: A, Position: 2 True
👉 Same object reused in memory.
Key Concept
Instead of:
new Character('A');
new Character('A');
new Character('A');
We do:
factory.GetCharacter('A');
👉 Shared object reused.
Diagram Understanding
Client ↓ FlyweightFactory ↓ Shared Flyweight Objects
👉 Factory manages reusable objects.
Intrinsic vs Extrinsic State
Intrinsic State (Shared)
Stored inside flyweight object:
Character Symbol
Extrinsic State (External)
Passed from outside:
- Position
- Color
- Font Size
👉 Helps reduce memory usage.
Advantages
- ✔ Reduces memory usage
- ✔ Improves performance
- ✔ Reuses objects efficiently
- ✔ Good for large-scale systems
Disadvantages
- ✖ Increased complexity
- ✖ Harder debugging
- ✖ State management can be tricky
When to Use
Use Flyweight Pattern when:
- Large number of similar objects exist
- Memory optimization is important
- Object creation is expensive
- Shared immutable data exists
Real Project Mapping (.NET + Angular)
| Feature | Usage |
|---|---|
| Cache systems | Flyweight |
| Shared UI icons | Flyweight |
| Game engines | Flyweight |
| Text rendering | Flyweight |
| Reusable configuration objects | Flyweight |
ASP.NET Core Real Example
IMemoryCache
_memoryCache.GetOrCreate("users", entry =>
{
return users;
});
👉 Shared cached object reused.
Advanced Example – Game Development
Tree Object ├── Shared Image ├── Shared Texture └── Different Positions
👉 Thousands of trees reuse same internal data.
Flyweight vs Singleton
| Flyweight | Singleton |
|---|---|
| Many shared objects | One shared object |
| Optimizes memory | Ensures single instance |
| Object pool/cache | Global access point |
Pro Tip
Flyweight Pattern works well with:
- Caching
- Object pooling
- Immutable objects
- High-performance systems
Summary
Flyweight Pattern helps you:
- Reduce memory usage
- Reuse shared objects
- Improve application performance
👉 Perfect for:
- Caching systems
- UI rendering
- Games
- Large-scale object management
Comments
Post a Comment