Understanding the Flyweight Method Design Pattern in C#

The Flyweight Method design pattern is a structural pattern that helps reduce memory usage by sharing as much data as possible with other similar objects. It is particularly useful in scenarios where a large number of objects with similar properties are needed. The Flyweight Method pattern achieves this by storing common data externally and referencing it, thereby minimizing memory consumption.
Understanding the Proxy Method Design Pattern in C#
Example Without the Flyweight Method Pattern
Let's consider a simple graphics application where we need to display a large number of circles with varying colors and coordinates. In a non-pattern approach, we might create a separate object for each circle, even if many circles share the same color.
using System;
using System.Collections.Generic;
namespace WithoutFlyweightMethodPattern
{
// Circle class with color, x and y coordinates
class Circle
{
public string Color { get; private set; }
public int X { get; private set; }
public int Y { get; private set; }
public Circle(string color, int x, int y)
{
Color = color;
X = x;
Y = y;
}
public void Draw()
{
Console.WriteLine($"Drawing Circle [Color: {Color}, X: {X}, Y: {Y}]");
}
}
// Client
class Program
{
static void Main(string[] args)
{
List<Circle> circles = new List<Circle>();
// Creating 1,000 circles with varying positions but only 5 colors
string[] colors = { "Red", "Green", "Blue", "Yellow", "Black" };
Random random = new Random();
for (int i = 0; i < 1000; i++)
{
string color = colors[random.Next(colors.Length)];
int x = random.Next(100);
int y = random.Next(100);
circles.Add(new Circle(color, x, y));
}
// Drawing all circles
foreach (var circle in circles)
{
circle.Draw();
}
}
}
}
Problems in the Non-Pattern Approach
High Memory Usage: Creating a new object for each circle, even if many share the same color, results in a large amount of memory being used.
Redundant Data: The same data (color) is stored multiple times, leading to redundancy and inefficiency.
How the Flyweight Method Pattern Solves These Problems
The Flyweight Method pattern minimizes memory usage by sharing common data (intrinsic state) among objects and storing unique data (extrinsic state) separately. In our example, the color is the intrinsic state, while the coordinates (x and y) are the extrinsic state.
Revisited Code with Flyweight Method Pattern
Let's implement the Flyweight Method pattern using a CircleFactory
to manage shared instances of circles with the same color.
using System;
using System.Collections.Generic;
namespace FlyweightMethodPattern
{
// Flyweight Interface
interface ICircle
{
void Draw(int x, int y);
}
// Concrete Flyweight
class Circle : ICircle
{
private string _color;
public Circle(string color)
{
_color = color;
}
public void Draw(int x, int y)
{
Console.WriteLine($"Drawing Circle [Color: {_color}, X: {x}, Y: {y}]");
}
}
// Flyweight Factory
class CircleFactory
{
private static Dictionary<string, Circle> _circleMap = new Dictionary<string, Circle>();
public static ICircle GetCircle(string color)
{
if (!_circleMap.ContainsKey(color))
{
_circleMap[color] = new Circle(color);
Console.WriteLine($"Creating circle of color : {color}");
}
return _circleMap[color];
}
}
// Client
class Program
{
static void Main(string[] args)
{
// Creating 1,000 circles with varying positions but only 5 colors
string[] colors = { "Red", "Green", "Blue", "Yellow", "Black" };
Random random = new Random();
for (int i = 0; i < 1000; i++)
{
string color = colors[random.Next(colors.Length)];
int x = random.Next(100);
int y = random.Next(100);
ICircle circle = CircleFactory.GetCircle(color);
circle.Draw(x, y);
}
}
}
}
Benefits of the Flyweight Method Pattern
Reduced Memory Usage: By sharing objects that have the same intrinsic state, the Flyweight Method pattern significantly reduces memory usage.
Efficiency: The pattern avoids redundancy by storing shared data centrally.
Scalability: It allows the creation of a large number of objects without a corresponding increase in memory usage.
Why Can't We Use Other Design Patterns Instead?
Singleton Pattern: The Singleton pattern ensures a single instance of a class, whereas the Flyweight Method pattern manages multiple instances with shared data.
Prototype Pattern: The Prototype pattern is about creating new objects by copying existing ones. It doesn't focus on sharing common data among objects.
Factory Method Pattern: While the Factory Method pattern is concerned with object creation, it doesn't inherently deal with sharing and minimizing memory usage like the Flyweight Method pattern.
Steps to Identify Use Cases for the Flyweight Method Pattern
Large Number of Similar Objects: Identify situations where you need a large number of objects with similar properties.
Memory Constraints: Use the Flyweight Method pattern when memory usage is a concern and you need to optimize resource usage.
Shared Intrinsic State: Determine if there are common properties (intrinsic state) that can be shared among objects.
Distinct Extrinsic State: Ensure that the unique properties (extrinsic state) can be managed separately from the shared state.
By applying the Flyweight Method design pattern, you can efficiently manage a large number of similar objects, reducing memory usage and improving system performance. This pattern is particularly valuable in scenarios where memory constraints are critical, such as in graphical applications or systems with limited resources.